import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive/hive.dart';

enum SecureStorageKey { url, jwt, email }

enum ConfigKey { twoPageMode }

class Config {
  Config({required this.twoPageMode, required this.fullscreen});

  static const String keyTwoPageMode = "twoPageMode";
  static const String keyFullscreen = "fullscreen";

  bool twoPageMode;
  bool fullscreen;
}

class StorageHelper {
  final sheetAccessTimesBox = "sheetAccessTimes";
  final configBox = "config";

  late FlutterSecureStorage secureStorage;

  StorageHelper() {
    AndroidOptions getAndroidOptions() =>
        const AndroidOptions(encryptedSharedPreferences: true);
    secureStorage = FlutterSecureStorage(aOptions: getAndroidOptions());
  }

  Future<String?> readSecure(SecureStorageKey key) {
    return secureStorage.read(key: key.name);
  }

  Future<void> writeSecure(SecureStorageKey key, String? value) {
    return secureStorage.write(key: key.name, value: value);
  }

  Future<Config> readConfig() async {
    final box = await Hive.openBox(configBox);
    return Config(
      twoPageMode: box.get(Config.keyTwoPageMode) ?? false,
      fullscreen: box.get(Config.keyFullscreen) ?? false,
    );
  }

  Future<void> writeConfig(Config config) async {
    final box = await Hive.openBox(configBox);
    box.put(Config.keyTwoPageMode, config.twoPageMode);
    box.put(Config.keyFullscreen, config.fullscreen);
  }

  Future<Map<String, DateTime>> readSheetAccessTimes() async {
    final box = await Hive.openBox(sheetAccessTimesBox);
    return box.toMap().map(
      (k, v) => MapEntry(k as String, DateTime.parse(v as String)),
    );
  }

  Future<void> writeSheetAccessTime(String uuid, DateTime datetime) async {
    final box = await Hive.openBox(sheetAccessTimesBox);
    await box.put(uuid, datetime.toIso8601String());
  }
}
