import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:hub/features/profile/data/data_sources/profile_local_data_source.dart';
import 'package:hub/features/storage/index.dart';

class StorageHelper implements StorageRepository {
  static final StorageHelper _instance = StorageHelper._internal();
  factory StorageHelper() => _instance;
  StorageHelper._internal();

  late BuildContext? _context;
  BuildContext? get context => _context;
  set context(BuildContext? context) => _context = context;

  late bool _isRecovered = false;
  bool get isRecovered => _isRecovered;
  set isRecovered(bool isRecovered) => _isRecovered = isRecovered;

  Future<void> init() async {
    await SecureStorage.instance.init();
    await SharedPreferencesStorage.instance.init();
    await DatabaseStorage.instance.init();

    String? isFirstRun = await SharedPreferencesStorage.instance
        .get(SharedPreferencesKey.isFirstRun.value);

    if (isFirstRun != 'false') {
      log('First run');
      await SharedPreferencesStorage.instance
          .set(SharedPreferencesKey.isFirstRun.value, false);
      await SecureStorage.instance.set(SecureStorageKey.isLogged.value, false);
    }
  }

  static BaseStorage getInstance(Storage storage) {
    switch (storage) {
      case Storage.secureStorage:
        return SecureStorage.instance;
      case Storage.sharedPreferences:
        return SharedPreferencesStorage.instance;
      default:
        return DatabaseStorage.instance;
    }
  }

  static BaseStorage getInstanceByKey(String key) {
    if (SecureStorageKey.values //
        .map((e) => e.value)
        .toList()
        .contains(key)) {
      return SecureStorage.instance;
    } else if (SharedPreferencesKey.values
        .map((e) => e.value)
        .toList()
        .contains(key)) {
      return SharedPreferencesStorage.instance;
    } else {
      return DatabaseStorage.instance;
    }
  }

  Future<String?> get(String key) async {
    return await getInstanceByKey(key).get(key);
  }

  Future<void> set<T>(String key, T value) async {
    return await getInstanceByKey(key).set(key, value);
  }

  Future<void> del(String key) async {
    return await getInstanceByKey(key).delete(key);
  }

  Future<void> clean(Storage storage) async {
    return await getInstance(storage).clearAll();
  }
}
