import 'dart:convert';

import 'package:http/http.dart' as http;

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

class CRUD {
  Future<dynamic> get({
    required String link,
    Map<String, dynamic>? payload,
  }) async {
    var url = Uri.parse(
      link,
    );
    var response = await http.post(
      url,
      body: payload,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization':
            'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials.toString()))}',
      },
    );
    Log.print('response: ${response.body}');
    Log.print('response: ${response.request}');
    Log.print('payload: $payload');
    // 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';
    Log.print('imagePathFull: $imagePathFull');
    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});
    Log.print('request.body: ${request.body}');
    request.headers.addAll(headers);
    Log.print('request.headers: ${request.headers}');

    http.StreamedResponse response = await request.send();
    Log.print('response: ${response}');

    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,
    );
    var response = await http.post(
      url,
      body: payload,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization':
            'Basic ${base64Encode(utf8.encode(AK.basicAuthCredentials))}',
      },
    );
    Log.print('payload: ${payload}');
    Log.print('response.request: ${response.request}');
    Log.print('response.body: ${response.body}');
    Log.print('response.reasonPhrase: ${response.reasonPhrase}');
    // print(response.statusCode);
    var jsonData = jsonDecode(response.body);
    if (response.statusCode == 200) {
      if (jsonData['status'] == 'success') {
        return response.body;
      } else {
        String errorMessage = jsonData['message'];
        Log.print('errorMessage: ${errorMessage}');
        // 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) {}
}
