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/urls.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/models/device/device_transfer_info.dart';
import 'package:test_sa/models/user.dart';

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

  //reset provider data
  void reset() {
    items = 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<DeviceTransfer> items;

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

  /// 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,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;

    // isLoading = false;
    // stateCode = 200;
    // items = [];
    // items.addAll(List.generate(20, (index) => DeviceTransfer(
    //   title: "ddddd",
    //   id: "5",
    //   device: Device(id: "1",brand: "brand",model: "model"),
    //   destinationClient: Hospital(name: "hospital name",id: "1"),
    //   destinationDepartment: Department(id: "5",name: "destination Department"),
    //   senderDepartment: Department(id: "5",name: "sender Department"),
    //   userId: "5"
    // )));
    // notifyListeners();
    // return 200;
    Response response;
    try {
      Map<String, dynamic> body = {};
      body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;

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

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

  Future<int> createRequest({
    @required String host,
    @required User user,
    @required DeviceTransfer model,
  }) async {
    Map<String, dynamic> body = {
      // "uid": user.id.toString(),
      // "token": user.token ?? "",
      "assetId": model.device.id ?? "",
      "destSiteId": model.receiver.client.id ?? "",
      "destDepartmentId": model.receiver.department.id ?? "",
      "senderSiteId": model.receiver.client.id ?? "",
    };

    Response response;
    try {
      response = await ApiManager.instance.post(URLs.requestDeviceTransfer, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          items.insert(0, DeviceTransfer.fromJson(json.decode(utf8.decode(response.bodyBytes))[0]));
          notifyListeners();
        }
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> updateRequest({
    @required String host,
    @required User user,
    @required bool isSender,
    @required int requestId,
    @required DeviceTransfer oldModel,
    @required DeviceTransferInfo newModel,
  }) async {
    Map<String, dynamic> body = {
      "id": oldModel.id,
      "assetId": oldModel.device.id ?? "",
      "senderSiteId": oldModel.sender.client.id,
      "destSiteId": oldModel.receiver.client.id,
      "destDepartmentId": oldModel.receiver.department.id,
    };

    if(isSender){
      body.addAll(
        {
          "senderSiteId": newModel.client.id,
          "senderDepartmentId":  newModel.department.id,
          "senderAssignedEmployeeId":  newModel.userId,
          "senderMachineStatusId": newModel.status.id,
          "senderComment": newModel.comment,
          "senderWorkingHours": newModel.workingHours,
          "senderTravelingHours": newModel.travelingHours,
          "senderAttachmentName": "${newModel.signature}.png",
        }
      );
    }else{
      body.addAll(
          {
            "destSiteId": newModel.client.id,
            "destDepartmentId":  newModel.department.id,
            "receiverAssignedEmployeeId":  newModel.userId,
            "receiverMachineStatusId": newModel.status?.id??"",
            "receiverComment": newModel.comment,
            "receiverWorkingHours": newModel.workingHours,
            "receiverTravelingHours": newModel.travelingHours,
            "receiverAttachmentName": "${newModel.signature}.png",
          }
      );
    }

    body.addAll(newModel.toJson(isSender));
    Response response;
    try{
      response = await ApiManager.instance.put(
          URLs.updateDeviceTransfer,
          body: body
      );

      print(response.body);
      print("${newModel.signature}.png");
      // response = await post(
      //   Uri.parse("$host${URLs.updateDeviceTransfer}/$requestId"),
      //   body: body,
      // );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset();
        // oldModel.fromDeviceTransfer(
        //   DeviceTransfer.fromJson(
        //       json.decode(utf8.decode(response.bodyBytes))[0]
        //   )
        // );
        notifyListeners();
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }
}