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';
  //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 Type = "Content-Type";
  String App_json = "application/json";

  // 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) {
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  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,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(feedback),
        headers: {Type: App_json}, body: json.encode(body));
    // print(res.body);
    // print(res.statusCode);
    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      return res.statusCode;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  // Future<String?> uploadFileToS3(File filePath, String filename) async {
  //   String accessKey = 'AKIA2I2EIAE4UUMUSYOO';
  //   String secretKey = '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';
  //   //String filePath = "path/to/file.txt";
  //   String bucket = 'surveilancesystem';
  //   String region = 'ap-south-1';
  //   //String fileName = b(filePath!.path);
  //   //File file = new File(filePath);
  //   // my_image.jpg
  //   try {
  //     String? response = await AwsS3.uploadFile(
  //         accessKey: accessKey,
  //         secretKey: secretKey,
  //         file: filePath,
  //         bucket: bucket,
  //         region: region,
  //         //contentType: 'binary/octet-stream',
  //         //key: filename,
  //         filename: filename,
  //         acl: ACL.public_read_write,
  //         metadata: {'upload': "video"});
  //     //print("File uploaded successfully!");
  //     return response;
  //   } catch (e) {
  //     return e.toString();
  //   }
  //   return '';
  // }
// //upload video file
//   Future<void> uploadVideoToS3(File videoFile) async {
//     final result =  await AwsS3.uploadFile(
//   accessKey: "AKxxxxxxxxxxxxx",
//   secretKey: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
//   file: File("path_to_file"),
//   bucket: "bucket_name",
//   region: "us-east-2",
//   metadata: {"test": "test"} // optional
// );
//     if (result.isFailure) {
//       throw Exception(result.errorMessage);
//     }
//   }
//  }

  Future<String?> empuploadVideo(
      File imagepath, String filename, String storename) async {
    try {
      //final request = http.MultipartRequest( 'POST', Uri.parse('https://plutokm.com/grc_capture_image2.php?barcode=$barcode&boothno=$no&updatesiblings=$siblings'));
      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();
      //var res = response.body;
      //print(response.);
      if (response.statusCode == 200) {
        return responseString;
      } else {
        return responseString;
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error in upload video $e");
      }
    }
    return null;
  }

// Alert Summary Post Request

  Future<String> geAlertSummary(String store, String date, String os) async {
    //print(date);
    Map<String, dynamic> body = {
      'store': store,
      'date': date,
      'platform': os,
    };
    var client = http.Client();
    var res = await client.post(Uri.parse(AlertSummary),
        headers: {Type: App_json}, body: json.encode(body));

    if (res.statusCode == 200) {
      //loginResponseFromJson(res as String);
      return res.body;
    } else {
      throw Exception('Status code was wrong$res.statusCode');
    }
  }

  Future<http.Response?> getFootFallVerify(
      String store, String hours, String selectdate) async {
    //print(date);
    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) {
      //loginResponseFromJson(res as String);
      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));
    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";
  }
}
