import 'dart:convert';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:http/http.dart' as http;

class RemoteData {
  String BaseUrl = 'http://vaman.plutokm.com/';
  String LoginUrl = 'http://vaman.plutokm.com/login_test';
  //String AlertSummary = 'http://vaman.plutokm.com/alert_summary_flutter';
  String AlertSummary = 'http://vaman.plutokm.com/alert_summary_flutter';
  String Review = 'http://vaman.plutokm.com/alerts_new';
  String EmpReport = 'http://vaman.plutokm.com/regstatusreport';
  String ImageUrl = 'http://vaman.plutokm.com/flutter';
  String UploadVideo = 'http://vaman.plutokm.com/registeration_video';
  String feedback = 'http://vaman.plutokm.com/api/mx_feedback_new';
  String AuditData = 'http://vaman.plutokm.com/audit_page';
  //String AuditData        = 'http://192.168.65.111:8088/audit_page';
  //String AuditupdateData  = 'http://192.168.65.111:8088/audit_update';
  String AuditupdateData = 'http://vaman.plutokm.com/audit_update';
  String ChangePassword = 'http://vaman.plutokm.com/changePassword';
  String FootFallVerify = 'http://vaman.plutokm.com/footfall_verify_flutter';
  String EmployeeStatus = 'http://vaman.plutokm.com/employees_status';
  String DepartmentSearch =
      'http://vaman.plutokm.com/employees_status_department_instore';
  String IssueVideos = 'http://vaman.plutokm.com/video_alert_page';
  String UpdateIssueVideos = 'http://vaman.plutokm.com/update_video_alert';
  String UpdateIssueVideos1 = 'http://vaman.plutokm.com/L2_update_video_alert';
  String Insights = 'http://vaman.plutokm.com/get_insights';
  String Type = "Content-Type";
  String App_json = "application/json";
  String speechtotext = 'http://192.168.65.112:5113/mobile_response2/';
  String pendingAlerts = 'http://vaman.plutokm.com/pending_alerts';
  String speechtotext1 = 'http://vaman.plutokm.com/llama_tool_1/';
  String speechtotext2 = 'http://vaman.plutokm.com/llama_tool_2/';
  String speechtotext3 = 'http://vaman.plutokm.com/llama_tool_3/';

  // Stores List Request GET Method
  // Login Request POST Method
  Future<String> getLoginRequest(
      String loginid, String pass, String token) async {
    Map<String, dynamic> body = {
      'login_id': loginid,
      'password': pass,
      'token': token,
      'os': Platform.isAndroid
          ? 'Android'
          : Platform.isIOS
              ? 'IOS'
              : 'Unknown',
    };
    if (kDebugMode) {
      print(body);
    }
    var client = http.Client();
    var res = await client.post(Uri.parse(LoginUrl),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      print(res.body);
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<String> getVoiceResponse(File text, String? userid) async {
    var header = {Type: App_json};
    var res = '';
    var url = '';
    if (kDebugMode) {
      print(userid);
    }
    if (text != null && userid != null) {
      //url = '$speechtotext3$text';
      url = 'http://vaman.plutokm.com/llama_tool_4';
      if (kDebugMode) {
        print(url);
      }

      try {
        final request = http.MultipartRequest('POST', Uri.parse(url));
        request.files
            .add(await http.MultipartFile.fromPath('image', text.path));
        //request.files.add(http.MultipartFile.fromString('body_image_path', image));
        //request.fields['style_code'] = stylecode;
        var response = await request.send();
        var responseString = await response.stream.bytesToString();
        if (kDebugMode) {
          print('Response   :$responseString');
        }
        res = responseString;
      } catch (e) {
        if (kDebugMode) {
          print(e);
        }
      }
      // var response = await http.post(
      //   Uri.parse(url),
      //   headers: header,
      // );
      // if (kDebugMode) {
      //   print(response.statusCode);
      // }
      // if (response.statusCode == 200) {
      //   res = response.body;
      //   if (kDebugMode) {
      //     print('Logout : $res');
      //   }
      // }
    }
    return res;
  }

  Future<String> getSpeechResponse(String text, String? userid) async {
    var header = {Type: App_json};
    var res = '';
    var url = '';
    if (kDebugMode) {
      print(userid);
    }
    if (text.isNotEmpty && userid != null) {
      if (userid == '1') {
        url = '$speechtotext1$text';
        if (kDebugMode) {
          print(url);
        }
      } else if (userid == '2') {
        url = '$speechtotext2$text';
        if (kDebugMode) {
          print(url);
        }
      } else {
        url = '$speechtotext3$text';
        //url = '$speechtotext3';
        if (kDebugMode) {
          print(url);
        }
      }

      var response = await http.post(
        Uri.parse(url),
        headers: header,
      );
      if (kDebugMode) {
        print(response.statusCode);
      }
      if (response.statusCode == 200) {
        res = response.body;
        if (kDebugMode) {
          print('Logout : $res');
        }
      }
    }
    return res;
  }

  Future<int> getFeedbackStatus(String notificationId, String userId,
      String feed, String comments) async {
    Map<String, dynamic> body = {
      'NotificationID': notificationId,
      'user_id': userId,
      'verified': 'Verified',
      'feedback': feed,
      'comments': comments,
    };
    //print(body);
    var client = http.Client();
    var res = await client.post(Uri.parse(feedback),
        headers: {Type: App_json}, body: json.encode(body));
    if (kDebugMode) {
      print(res.body);
    }
    if (kDebugMode) {
      print(res.statusCode);
    }
    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      return res.statusCode;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
    //return 200;
  }

  Future<String?> empuploadVideo(
      File imagepath, String filename, String storename) async {
    try {
      final request = http.MultipartRequest(
          'Post', Uri.parse('http://192.168.65.111:8080/zoom'));
      request.files
          .add(await http.MultipartFile.fromPath('video_path', imagepath.path));
      request.fields['empid'] = '78';
      request.fields['store_name'] = 'KLM AMEERPET';
      request.fields['file'] = filename;
      var response = await request.send();
      var responseString = await response.stream.bytesToString();
      if (response.statusCode == 200) {
        return responseString;
      } else {
        return responseString;
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error in upload video $e");
      }
    }

    return null;
  }

  Future<String> getpendingAlerts(String store, String date) async {
    Map<String, dynamic> body = {
      'store': store,
      'date': date,
    };
    print(body);
    var client = http.Client();
    var res = await client.post(Uri.parse(pendingAlerts),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  //Insights

  Future<String> getInsights(String region, String store, String date) async {
    Map<String, dynamic> body = {
      'region': region,
      'store': store,
      'date': date,
      'os': Platform.isAndroid
          ? 'Android'
          : Platform.isIOS
              ? 'IOS'
              : 'Unknown',
    };
    if (kDebugMode) {
      print(body);
    }
    var client = http.Client();
    var res = await client.post(Uri.parse(Insights),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

// Alert Summary Post Request

  Future<String> geAlertSummary(String store, String date) async {
    Map<String, dynamic> body = {
      'store': store,
      'date': date,
      'platform': Platform.isAndroid
          ? 'Android'
          : Platform.isIOS
              ? 'IOS'
              : 'Unknown',
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(AlertSummary),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<http.Response?> getFootFallVerify(
      String store, String hours, String selectdate) async {
    Map<String, dynamic> body = {
      'store': store,
      'hours': hours,
      'date': selectdate,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(FootFallVerify),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      if (kDebugMode) {
        print(res.body);
      }
      return res;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<http.Response?> getEmployeesStatus(String store) async {
    //print(date);
    Map<String, dynamic> body = {
      'store': store,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(EmployeeStatus),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      if (kDebugMode) {
        print(res.body);
      }
      return res;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<http.Response?> getDepartmentSearch(
      String store, String dept, String empid) async {
    if (kDebugMode) {
      print(store);
    }
    Map<String, dynamic> body = {
      'store': store,
      'department': dept,
      'login_id': empid,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(DepartmentSearch),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      if (kDebugMode) {
        print(res.body);
      }
      return res;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<String> getChangePassword(
      String oldpass, String newpass, String userid) async {
    //print(date);
    Map<String, dynamic> body = {
      'old_password': oldpass,
      'new_password': newpass,
      'user_id': userid,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(ChangePassword),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      if (kDebugMode) {
        print(res.body);
      }
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<String> getWeekly(String store, bool isvisble) async {
    //print(date);
    Map<String, dynamic> body = {
      'store': store,
      'active': isvisble,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(AuditData),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      if (kDebugMode) {
        print(res.body);
      }
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<String> getWeeklyUpdate(
      String userid, String store, List<Map<String, dynamic>> array) async {
    Map<String, dynamic> body = {
      'userid': userid,
      'store': store,
      'auditdata': array,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(AuditupdateData),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      if (kDebugMode) {
        print(res.body);
      }
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<String> getImageUrl(String? path, String? resp) async {
    Map<String, dynamic> body = {
      'key': path,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(ImageUrl),
        headers: {Type: App_json}, body: json.encode(body));
    var jsonMap = jsonDecode(res.body);
    return jsonMap['url'];
  }

  Future<String> getUserReport(String storeName) async {
    Map<String, dynamic> body = {
      'STORE': storeName,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(EmpReport),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception(res.statusCode);
    }
  }

  Future<String> getIssueVideos(String storeName) async {
    Map<String, dynamic> body = {
      'store': storeName,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(IssueVideos),
        headers: {Type: App_json}, body: json.encode(body));
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception(res.statusCode);
    }
  }

  Future<String> getUpdateIssueVideos(String id, String comment) async {
    Map<String, dynamic> body = {
      'vidnotid': id,
      'comment': comment,
    };
    if (kDebugMode) {
      print(body);
    }
    var client = http.Client();
    var res = await client.post(Uri.parse(UpdateIssueVideos),
        headers: {Type: App_json}, body: json.encode(body));
    if (kDebugMode) {
      print('Status Code :$res.statusCode');
    }
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception(res.statusCode);
    }
  }

  Future<String> getUpdateIssueVideos1(String id, String comment) async {
    Map<String, dynamic> body = {
      'vidnotid': id,
      'comment': comment,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(UpdateIssueVideos1),
        headers: {Type: App_json}, body: json.encode(body));
    if (kDebugMode) {
      print('Status Code :$res.statusCode');
    }
    if (res.statusCode == 200) {
      return res.body;
    } else {
      throw Exception(res.statusCode);
    }
  }

// Review
// { "store":"KLM DSNR",
//   "date":"2022-09-29"
// }

  Future<String> getFootFall(String store, String day) async {
    //print(date);
    Map<String, dynamic> body = {
      "store": store,
      'platform': Platform.isAndroid
          ? 'Android'
          : Platform.isIOS
              ? 'IOS'
              : 'Unknown',
      "day": day
    };
    var client = http.Client();
    var res = await client.post(
        Uri.parse('http://vaman.plutokm.com/footfall_flutter'),
        headers: {Type: App_json},
        body: json.encode(body));
    //print(res.body);
    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<http.Response?> getReview(
    String store,
    String date,
  ) async {
    Map<String, String>? headers = const {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {
      'store': store,
      'date': date,
    };
    var response = await http.post(
      Uri.parse(Review),
      body: jsonEncode(body),
      headers: headers,
    );
    return _handledResponse(response);
  }

  Future<http.Response> getNotificationReport(String store, String date) async {
    Map<String, String>? headers = const {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {
      'STORENAME': store,
      'Date': date,
    };
    var response = await http.post(Uri.parse('http://vaman.plutokm.com/report'),
        body: jsonEncode(body), headers: headers);
    return _handledResponse(response);
  }

  Future<http.Response> getValidEmp(String empid) async {
    Map<String, String>? headers = const {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {
      'employee_id': empid,
    };
    var response = await http.post(
      Uri.parse('http://vaman.plutokm.com/idverify'),
      body: jsonEncode(body),
      headers: headers,
    );
    // if (response.statusCode == 200) {
    return _handledResponse(response);
    //return _handledResponse(response);
  }
//   Future<http.Response> UploadEmpVideo(String File, String filepath) async{
//     Map<String, String>? headers = const {'Content-Type': 'application/json'};
//     Map<String, dynamic> body = {
//       'employee_id': File,
//     };
//   var response = await http.post(
//       Uri.parse(UploadVideo),
//       body: jsonEncode(body),
//       headers: headers,
//     );
//     return _handledResponse(response);
//   }

  Future<String> UploadEmpVideo(
    File uploadpath,
    String filename,
    String empid,
    String store,
  ) async {
    try {
      final request = http.MultipartRequest('POST', Uri.parse(UploadVideo));
      request.files.add(await http.MultipartFile.fromPath(
        'upload_path',
        uploadpath.path,
      ));
      request.fields['empid'] = empid;
      request.fields['store_name'] = store;
      var response = await request.send();
      //print(response.);
      if (response.statusCode == 200) {
        return response.stream.bytesToString();
      } else {
        throw Exception(response.statusCode);
      }
    } catch (e) {
      return e.toString();
    }
  }

  Future<http.Response> _handledResponse(
    http.Response response,
  ) async {
    // if (response.body!['auth'] == false) {
    //  LogoutDialog().logout();
    //  return null;
    // }

    switch (response.statusCode) {
      case 200:
        return response;
      case 201:
        return response;
      case 400:
        //throw BadRequestException(response.toString());
        return response;
      case 401:
      case 403:
        return response;
      //throw UnauthorizedException(response.toString());
      case 500:
        return response;
      default:
        return response;
      // throw FetchDataException(
      //     "Error occurred while communicating with server with StatusCode : ${response.statusCode}");
    }
  }

  Future<String> getImgeUrl(String? path, String? filenamewithext) async {
    // final s3Options = S3Service(
    //  accessKey: 'YOUR_ACCESS_KEY',
    //  secretKey: 'YOUR_SECRET_KEY',
    //  region: 'YOUR_REGION',
    // );
    //  //var url = '';
    //   final s3 = Boto3(
    //     regionName: 'ap-south-1',
    //     accessKeyId: 'AKIA2I2EIAE4UUMUSYOO',
    //     secretAccessKey: '7ii8F5NReZQwNR0MURVzuHlZ2BL9oRSkvfgzTV1Y',
    //   ).client('s3');
    // const bucketName = 'surveilancesystem';
    // final objectKey = path;
    // File file = File(path!);
    // http.Response s3ObjectUrl = await awsS3Client.getObject(filenamewithext!);
    // print(s3ObjectUrl.statusCode);
    // print(s3ObjectUrl.body);
    //   s3Client = S3Client(
    //   region: 'your-aws-region',
    //   accessKey: 'your-aws-access-key',
    //   secretKey: 'your-aws-secret-key',
    // );
    // AwsS3PluginFlutter awsS3 = AwsS3PluginFlutter(
    //   awsFolderPath: path,
    //   fileNameWithExt: filenamewithext,
    //   region: Regions.AP_SOUTH_1,
    //   bucketName: 'surveilancesystem',
    //   AWSAccess: 'AKIA2I2EIAE4UUMUSYOO',
    //   AWSSecret: '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');
    //   String presigned = await awsS3.getPreSignedURLOfFile;
    // final url = s3.generatePresignedUrl(
    //   'getObject',
    //   Params: {
    //     'Bucket': bucketName,
    //     'Key': objectKey,
    //   },
    //   Expires: 60 * 5, // 5 minutes
    // );
    return '';
  }

  // Future<String> getReview(String store, String date) async {
  //   var headers = {'Content-Type': 'application/json'};
  //   Map<String, dynamic> body = {
  //     'store': store,
  //      'date': date,
  //   };
  //   var request = http.Request(
  //       'POST', Uri.parse('http://vaman.plutokm.com/regstatusreport'));
  //   request.body = json.encode({"STORE": "KLM AMEERPET"});
  //   request.headers.addAll(headers);
  //   http.StreamedResponse response = await request.send();
  //   if (response.statusCode == 200) {
  //     print(await response.stream.bytesToString());
  //   } else {
  //     print(response.reasonPhrase);
  //   }
  // }
}

class FetchDataException extends CustomException {
  FetchDataException([message])
      : super(message, "Error during communication: ");
}

class BadRequestException extends CustomException {
  BadRequestException([message]) : super(message, "Invalid request: ");
}

class UnauthorizedException extends CustomException {
  UnauthorizedException([message]) : super(message, "Unauthorized: ");
}

class InvalidInputException extends CustomException {
  InvalidInputException([message]) : super(message, "Invalid  input: ");
}

class CustomException implements Exception {
  final dynamic _prefix;
  final dynamic _message;

  CustomException([this._message, this._prefix]);

  @override
  String toString() {
    return "$_prefix$_message";
  }
}
