import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:service/constant/char_map.dart';

import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import 'encrypt_decrypt.dart';
import 'initilize.dart';

class CRUD {
  var dev;
  getJWT() async {
    var dev = Platform.isAndroid ? 'android' : 'ios';
    var payload = {
      'password': AK.passnpassenger,
      // 'email': box.read(BoxName.email),
      'aud': '${AK.allowed}$dev',
    };
    // if (box.read(BoxName.firstTimeLoadKey).toString() != 'false') {
    var response0 = await http.post(
      Uri.parse(AppLink.jwtService),
      body: payload,
    );

    if (response0.statusCode == 200) {
      final decodedResponse1 = jsonDecode(response0.body);

      final jwt = decodedResponse1['jwt'];
      box.write(BoxName.jwt, X.c(X.c(X.c(jwt, cn), cC), cs));

      await AppInitializer().getAIKey(Service.keyOfApp);
      await AppInitializer().getAIKey(Service.initializationVector);
      await Future.delayed(Duration.zero);
      await EncryptionHelper.initialize();

      await AppInitializer().getAIKey(Service.FCM_PRIVATE_KEY);
      box.write(BoxName.firstTimeLoadKey, 'false');
      // await AppInitializer().getKey();
    } else {}
  }

  Future<dynamic> get({
    required String link,
    Map<String, dynamic>? payload,
  }) async {
    var url = Uri.parse(
      link,
    );
    bool isTokenExpired = JwtDecoder.isExpired(X
        .r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
        .toString()
        .split(AppInformation.addd)[0]);

    if (isTokenExpired) {
      await getJWT();
    }
    var response = await http.post(
      url,
      body: payload,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization':
            'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
      },
    );
    print(response.body);
    // if (response.statusCode == 200) {
    var jsonData = jsonDecode(response.body);
    if (jsonData['status'] == 'success') {
      return response.body;
    }

    return jsonData['status'];
  }

  // }
  Future<dynamic> arabicTextExtractByVisionAndAI({
    required String imagePath,
    required String driverID,
  }) async {
    var headers = {
      'Content-Type': 'application/json',
      'Ocp-Apim-Subscription-Key': AK.ocpApimSubscriptionKey
    };

    String imagePathFull =
        '${AppLink.server}/card_image/$imagePath-$driverID.jpg';
    var request = http.Request(
        'POST',
        Uri.parse(
            'https://eastus.api.cognitive.microsoft.com/computervision/imageanalysis:analyze?features=caption,read&model-version=latest&language=en&api-version=2024-02-01'));
    request.body = json.encode({"url": imagePathFull});
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      return await response.stream.bytesToString();
    } else {}
  }

  Future<dynamic> getAgoraToken({
    required String channelName,
    required String uid,
  }) async {
    var uid = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);
    var res = await http.get(Uri.parse(
            // 'https://repulsive-pig-rugby-shirt.cyclic.app/token?channelName=$channelName'),
            'https://orca-app-b2i85.ondigitalocean.app/token?channelName=$channelName'),
        // headers: {'Authorization': 'Bearer ${AK.agoraAppCertificate}'});
        headers: {'Authorization': 'Bearer '});

    if (res.statusCode == 200) {
      var response = jsonDecode(res.body);
      return response['token'];
    } else {}
  }

  Future<dynamic> getLlama({
    required String link,
    required String payload,
    required String prompt,
  }) async {
    var url = Uri.parse(
      link,
    );
    var headers = {
      'Content-Type': 'application/json',
      'Authorization':
          'Bearer LL-X5lJ0Px9CzKK0HTuVZ3u2u4v3tGWkImLTG7okGRk4t25zrsLqJ0qNoUzZ2x4ciPy'
      // 'Authorization': 'Bearer ${Env.llamaKey}'
    };
    var data = json.encode({
      "model": "Llama-3-70b-Inst-FW",
      // "model": "llama-13b-chat",
      "messages": [
        {
          "role": "user",
          "content":
              "Extract the desired information from the following passage as json decoded like $prompt just in this:\n\n$payload"
        }
      ],
      "temperature": 0.9
    });
    var response = await http.post(
      url,
      body: data,
      headers: headers,
    );

    if (response.statusCode == 200) {
      return response.body;
    }
    return response.statusCode;
  }

  Future<dynamic> post({
    required String link,
    Map<String, dynamic>? payload,
  }) async {
    // String? basicAuthCredentials =
    //     await storage.read(key: BoxName.basicAuthCredentials);
    var url = Uri.parse(
      link,
    );
    bool isTokenExpired = JwtDecoder.isExpired(X
        .r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
        .toString()
        .split(AppInformation.addd)[0]);

    if (isTokenExpired) {
      await getJWT();
    }
    var response = await http.post(
      url,
      body: payload,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization':
            'Bearer ${X.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs).toString().split(AppInformation.addd)[0]}'
      },
    );
    var jsonData = jsonDecode(response.body);
    if (response.statusCode == 200) {
      if (jsonData['status'] == 'success') {
        return response.body;
      } else {
        String errorMessage = jsonData['message'];
        // Get.snackbar('Error'.tr, errorMessage.tr,
        //     backgroundColor: AppColor.redColor);
        return (jsonData['status']);
      }
    } else {
      return response.statusCode;
    }
  }

  sendEmail(
    String link,
    Map<String, String>? payload,
  ) async {
    var headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      'Authorization':
          'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
    };
    var request = http.Request('POST', Uri.parse(link));
    request.bodyFields = payload!;
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();
    if (response.statusCode == 200) {
    } else {}
  }

  Future<dynamic> update({
    required String endpoint,
    required Map<String, dynamic> data,
    required String id,
  }) async {
    // String? basicAuthCredentials =
    //     await storage.read(key: BoxName.basicAuthCredentials);
    var url = Uri.parse('$endpoint/$id');
    var response = await http.put(
      url,
      body: json.encode(data),
      headers: {
        'Authorization':
            'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
      },
    );
    return json.decode(response.body);
  }

  Future<dynamic> delete({
    required String endpoint,
    required String id,
  }) async {
    // String? basicAuthCredentials =
    //     await storage.read(key: BoxName.basicAuthCredentials);
    var url = Uri.parse('$endpoint/$id');
    var response = await http.delete(
      url,
      headers: {
        'Authorization':
            'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
      },
    );
    return json.decode(response.body);
  }

  extractTextFromLines(json) {}
}
