import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/issue.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/service_report.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/models/service_request/service_request_search.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/models/user.dart';

class ServiceRequestsProvider extends ChangeNotifier {
  // number of items call in each request
  final pageItemNumber = 10;

  //reset provider data
  void reset() {
    serviceRequests = null;
    nextPage = true;
    stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int stateCode;

  // true if there is next page in product list and false if not
  bool nextPage = true;

  // list of user requests
  List<ServiceRequest> serviceRequests;

  // when requests in-process _loading = true
  // done _loading = true
  // failed _loading = false
  bool isLoading;

  ServiceRequestSearch search = ServiceRequestSearch();

  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> getRequests({
    @required String host,
    @required User user,
    @required int hospitalId,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (serviceRequests == null) notifyListeners();
    Response response;
    try {
      Map<String, dynamic> body = {};
      body.addAll(search.toMap());
      body["pageNumber"] = (serviceRequests?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;

      response = await ApiManager.instance.post(
        URLs.getServiceRequests,
        body: body,
      );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List requestsListJson = json.decode(response.body)["data"];
        List<ServiceRequest> serviceRequestsPage = requestsListJson.map((request) => ServiceRequest.fromJson(request)).toList();
        serviceRequests ??= [];
        serviceRequests.addAll(serviceRequestsPage);
        if (serviceRequestsPage.length == pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<ServiceRequest> getSingleServiceRequest({
    @required String requestId,
    @required String host,
    @required User user,
    @required Subtitle subtitle,
  }) async {
    String userData = '';
    if (user != null) {
      userData += "&uid=" + user.id;
      userData += "&token=" + user.token;
    }

    Response response;
    try {
      response = await get(Uri.parse(
        host +
            URLs.getSingleServiceRequest +
            '?call_nid=$requestId'
                '$userData',
      ));
    } catch (error) {
      throw (HttpStatusManger.getStatusMessage(status: -1, subtitle: subtitle));
    }

    // If the call to the server was successful, parse the JSON.
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // If the call to the server was successful, parse the JSON.
      List jsonList = json.decode(utf8.decode(response.bodyBytes).replaceAll("\\", ""));
      List<ServiceRequest> _requests = jsonList.map((i) => ServiceRequest.fromJson(i)).toList();
      return _requests[0];
    } else {
      throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: subtitle));
    }
  }

  Future<int> createRequest({
    @required String host,
    @required User user,
    @required ServiceRequest serviceRequest,
  }) async {
    var body = {
      "callCreatedBy": {"id": user.id, "name": user.userName},
      "assets": serviceRequest.deviceId == null ? [] : [serviceRequest.deviceId],
      "requestedDate": DateTime.now().toIso8601String(),
      "requestedTime": DateTime.now().toIso8601String(),
      "client": user.hospital?.id ?? '',
      "callComments": serviceRequest.maintenanceIssue,
      "attachmentsCallRequest": serviceRequest.devicePhotos.map((e) => {"name": e}).toList(),
      "priority": serviceRequest.priority.toMap(),
      "defectType": serviceRequest.defectType.toMap(),
      "typeofRequest": serviceRequest.type.toMap(),
      "requestedThrough": serviceRequest.type.toMap(),
    };
    if (serviceRequest.audio != null) {
      body["voiceNote"] = serviceRequest.audio;
    }
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.createRequest, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (serviceRequests != null) serviceRequests.insert(0, ServiceRequest.fromJson(json.decode(utf8.decode(response.bodyBytes))[0]));
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> createIssueReport({
    @required String host,
    @required User user,
    @required Issue issue,
  }) async {
    Response response;
    Map<String, String> body = issue.toMap();
    body["uid"] = user.id;
    body["token"] = user.token;
    try {
      response = await post(
        Uri.parse(host + URLs.createReport),
        body: body,
      );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {}
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> updateDate({
    @required String host,
    @required User user,
    @required String newDate,
    @required Lookup employee,
    @required ServiceRequest request,
  }) async {
    Response response;
    var body = {
      "callCreatedBy": {"id": user.id, "name": user.userName},
      "assets": request.deviceId == null ? [] : [request.deviceId],
      "requestedDate": newDate,
      "requestedTime": newDate,
    };
    try {
      response = await ApiManager.instance.put(
        URLs.updateRequestDate,
        body: body,
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        request.engineerName = employee.name;
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> createServiceReport({
    @required String host,
    @required User user,
    @required ServiceReport report,
    @required ServiceRequest request,
  }) async {
    Response response;
    try {
      Map<String, dynamic> body = report.toMap(request);
      // body["uid"] = user.id;
      // body["token"] = user.token;
      response = await ApiManager.instance.post(URLs.createServiceReport, body: body);
      print(response.body);
      // response = await post(
      //     Uri.parse(
      //   host+URLs.createServiceReport),
      //   body: body,
      // );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> createDuplicatedReport({
    @required String host,
    @required User user,
    @required ServiceRequest request,
  }) async {
    Response response;
    String userData = '';
    if (user != null) {
      userData += "&uid=" + user.id;
      userData += "&token=" + user.token;
    }

    try {
      response = await get(
        Uri.parse(host + URLs.createDuplicatedReport + "?nid=${request.id}" + userData),
      );

      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> updateServiceReport({
    @required String host,
    @required User user,
    @required ServiceReport report,
    @required ServiceRequest request,
  }) async {
    Response response;
    //Map<String,dynamic> body = report.toMap(request);
    // body["uid"] = user.id;
    // body["token"] = user.token;
    // body["job_id"] = request.id;
    // body["report_id"] = request.reportID;
    try {
      Map<String, dynamic> body = report.toMap(request);
      // body["uid"] = user.id;
      // body["token"] = user.token;
      response = await ApiManager.instance.put(URLs.updateServiceReport, body: body);
      // response = await post(
      //   Uri.parse(
      //       host+URLs.updateServiceReport),
      //   body: body,
      // );
      // stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> updateServiceReportTimer({
    @required String host,
    @required User user,
    @required TimerModel timer,
    @required ServiceRequest request,
  }) async {
    Response response;
    Map<String, dynamic> body = {};
    body["uid"] = user.id;
    body["token"] = user.token;
    body["job_id"] = request.id;
    body["start_time"] = (timer.startAt.millisecondsSinceEpoch / 1000).toStringAsFixed(0);
    body["end_time"] = (timer.endAt.millisecondsSinceEpoch / 1000).toStringAsFixed(0);
    body["working_hours"] = (timer.durationInSecond / 60 / 60).toStringAsFixed(5);
    body["report_id"] = request.reportID;
    try {
      response = await post(
        Uri.parse(host + URLs.updateServiceReport),
        body: body,
      );
      //stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // reset();
        // notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<ServiceReport> getSingleServiceReport({
    @required int reportId,
    @required String host,
    @required User user,
    @required Subtitle subtitle,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.get(
        URLs.getServiceReport + "?workOrderId=$reportId",
      );
    } catch (error) {
      throw (HttpStatusManger.getStatusMessage(status: -1, subtitle: subtitle));
    }

    // If the call to the server was successful, parse the JSON.
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // If the call to the server was successful, parse the JSON.
      return ServiceReport.fromJson(json.decode(response.body)["data"], reportId);
    } else {
      throw (HttpStatusManger.getStatusMessage(status: response.statusCode, subtitle: subtitle));
    }
  }
}
