import 'dart:convert';

import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/info.dart';
import 'package:Intaleq/controller/auth/login_controller.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:secure_string_operations/secure_string_operations.dart';

import '../../constant/char_map.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import 'crud.dart';
import 'encrypt_decrypt.dart';

class SecureStorage {
  void saveData(String key, value) async {
    await storage.write(key: key, value: value);
  }

  Future<String?> readData(String boxName) async {
    final String? value = await storage.read(key: boxName);
    return value.toString();
  }
}

const List<String> keysToFetch = [
  'serverPHP',
  // 'seferAlexandriaServer',
  // 'seferPaymentServer',
  // 'seferCairoServer',
  // 'seferGizaServer',
];

class AppInitializer {
  List<Map<String, dynamic>> links = [];

  Future<void> initializeApp() async {
    if (box.read(BoxName.jwt) == null) {
      await LoginController().getJWT();
    } else {
      bool isTokenExpired = JwtDecoder.isExpired(
          r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);

      if (isTokenExpired) {
        await LoginController().getJWT();
      }
    }

    // await getKey();
  }

  getAIKey(String key1) async {
    if (box.read(BoxName.firstTimeLoadKey) == null) {
      var res =
          await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});
      if (res != 'failure') {
        var d = jsonDecode(res)['message'];
        storage.write(key: key1, value: d[key1].toString());
      } else {}
    }
  }

  Future<void> getKey() async {
    try {
      var res =
          await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
      if (res != 'failure') {
        links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);
        await box.remove(BoxName.locationName);
        await box.remove(BoxName.basicLink);
        await box.remove(links[4]['name']);
        await box.remove(links[1]['name']);
        await box.remove(links[2]['name']);
        await box.write(BoxName.locationName, links);
        await box.write(BoxName.basicLink, (links[0]['server_link']));
        await box.write(links[2]['name'], (links[2]['server_link']));
        await box.write(links[1]['name'], (links[3]['server_link']));
        await box.write(links[3]['name'], (links[1]['server_link']));
        await box.write(BoxName.paymentLink, (links[4]['server_link']));
      }
    } catch (e) {}
  }
}
