import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get/get.dart';

import 'package:f0ckapp/utils/animatedtransition.dart';

class _StorageKeys {
  static const String muted = 'muted';
  static const String crossAxisCount = 'crossAxisCount';
  static const String drawerSwipeEnabled = 'drawerSwipeEnabled';
  static const String transitionType = 'transitionType';
}

class SettingsController extends GetxController {
  final EncryptedSharedPreferencesAsync storage =
      EncryptedSharedPreferencesAsync.getInstance();

  RxBool muted = false.obs;
  Rx<PageTransition> transitionType = PageTransition.opacity.obs;
  RxBool drawerSwipeEnabled = true.obs;
  RxInt crossAxisCount = 0.obs;

  RxInt videoControlsTimerNotifier = 0.obs;
  RxInt hideControlsNotifier = 0.obs;

  @override
  void onInit() {
    super.onInit();
    loadSettings();
  }

  void toggleMuted() {
    muted.value = !muted.value;
    saveSettings();
  }

  void setMuted(bool value) {
    muted.value = value;
    saveSettings();
  }

  Future<void> setTransitionType(PageTransition type) async {
    transitionType.value = type;
    await saveSettings();
  }

  Future<void> setCrossAxisCount(int value) async {
    crossAxisCount.value = value;
    await saveSettings();
  }

  Future<void> setDrawerSwipeEnabled(bool enabled) async {
    drawerSwipeEnabled.value = enabled;
    await saveSettings();
  }

  void resetVideoControlsTimer() => videoControlsTimerNotifier.value++;
  void hideVideoControls() => hideControlsNotifier.value++;

  Future<void> loadSettings() async {
    muted.value = await storage.getBoolean(_StorageKeys.muted) ?? false;
    crossAxisCount.value =
        await storage.getInt(_StorageKeys.crossAxisCount) ?? 0;
    drawerSwipeEnabled.value =
        await storage.getBoolean(_StorageKeys.drawerSwipeEnabled) ?? true;
    transitionType.value = PageTransition
        .values[await storage.getInt(_StorageKeys.transitionType) ?? 0];
  }

  Future<void> saveSettings() async {
    await storage.setBoolean(_StorageKeys.muted, muted.value);
    await storage.setInt(_StorageKeys.crossAxisCount, crossAxisCount.value);
    await storage.setBoolean(
      _StorageKeys.drawerSwipeEnabled,
      drawerSwipeEnabled.value,
    );
    await storage.setInt(
      _StorageKeys.transitionType,
      transitionType.value.index,
    );
  }
}
