import 'dart:developer';

import 'package:hub/features/menu/index.dart';
import 'package:hub/features/module/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/custom_functions.dart';

class MenuRepositoryImpl implements MenuRepository {
  final MenuLocalDataSource menuDataSource = MenuLocalDataSourceImpl();

  @override
  Future<List<MenuItem?>> entries2Items(
      List<MenuEntry> menuEntries, EnumMenuItem menuItem) async {
    List<MenuItem?> entries = [];
    // final bool isNewVersion = await StorageHelper().get(KeychainStorageKey.isNewVersion.value).then((v) => v.toBoolean());

    try {
      for (var entry in menuEntries) {
        final bool isDefault = await menuDataSource.processDisplayDefault(
            menuItem, entry, entries);
        if (isDefault) continue;
        final licenseValue = await LicenseRepositoryImpl().getModule(entry.key);
        if (licenseValue != null) {
          final licenseMap = await stringToMap(licenseValue);
          final display = EnumDisplay.fromString(licenseMap['display']);
          final startDate = licenseMap['startDate'] ?? '';
          final expirationDate = licenseMap['expirationDate'] ?? '';
          final isStarted =
              await menuDataSource.processStartDate(startDate, entry);
          final isExpired =
              await menuDataSource.processExpirationDate(expirationDate, entry);
          if (isStarted && !isExpired) {
            await menuDataSource.handleMenu(menuItem, display, entry, entries);
          }
          if (isExpired) {
            log('Entry ${entry.key} is expired');
            await menuDataSource.handleMenu(
                menuItem, EnumDisplay.inactive, entry, entries);
          }
          if (!isStarted) {
            log('Entry ${entry.key} is not started');
            await menuDataSource.handleMenu(
                menuItem, EnumDisplay.inactive, entry, entries);
          }
        }
      }
    } catch (e, s) {
      log('Error generating menu entries: $e', stackTrace: s);
    }
    return entries;
  }

  Future<EnumDisplay> processDisplay(
      Map<String, dynamic> module, bool isNewVersion) async {
    if (await _shouldUpdateDisplay(module, isNewVersion)) {
      final displayValue =
          module['display'] == EnumDisplay.active ? 'VISIVEL' : 'INVISIVEL';
      await LicenseLocalDataSourceImpl(DatabaseService.database)
          .setDisplayByKey(['FRE-HUB-ABOUT-PROPERTY'], displayValue);
      return EnumDisplay.fromString(displayValue);
    }

    return EnumDisplay.fromString(module['display']);
  }

  Future<bool> _shouldUpdateDisplay(
      Map<String, dynamic> module, bool isNewVersion) async {
    const keysToCheck = [
      LicenseKeys.residents,
      LicenseKeys.vehicles,
      LicenseKeys.openedVisits
    ];
    return isNewVersion && keysToCheck.any((key) => module['key'] == key.value);
  }
}
