import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_core/hive_registrar.g.dart';

class GService extends GetxService {
  final String _boxName = "appBox";

  late final Box<AppModel> box;

  Future<void> init() async {
    Hive.registerAdapters();
    box = await Hive.openBox<AppModel>(_boxName);
  }

  bool isFirstTime() {
    return box.values.isEmpty;
  }

  Module? getSelectedModule() {
    if (isFirstTime()) {
      return null;
    }
    var res = box.values.first.selectedModule;
    return res;
  }

  Future<void> saveSelectedModule(Module module) async {
    AppModel model = box.values.first;
    model
      ..isFirstRun = false
      ..selectedModule = module;

    await model.save();
  }

  Future<void> clearSelectedModule() async {
    AppModel model = box.values.first;
    model.selectedModule = null;
    await model.save();
  }

  TargetPage? getTargetPage(Module? module) {
    if (isFirstTime()) {
      return null;
    }
    var res = box.values.first.targetPages?.firstWhereOrNull((element) => element.module == module);
    return res;
  }

  Future<void> saveRoute(Module module, String route) async {
    AppModel model = box.values.first;

    TargetPage? targetPage = model.targetPages?.firstWhere((element) => element.module == module);
    if (targetPage != null) {
      targetPage.route = route;
      model.save();
    }
  }

  String? getRoute(Module module) {
    return getTargetPage(module)?.route;
  }

  Future<void> saveRole(Module module, String role) async {
    AppModel model = box.values.first;
    TargetPage? targetPage = model.targetPages?.firstWhere((element) => element.module == module);
    if (targetPage != null) {
      targetPage.selectedRole = role;
      model.save();
    }
  }

  String? getRole(Module module) {
    return getTargetPage(module)?.selectedRole;
  }

  Future<void> setIsNotFirstTime() async {
    AppModel model = AppModel(isFirstRun: false);

    await box.add(model);
  }
}
