import 'dart:convert';
import 'dart:developer';

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

import '../../../models/hospital.dart';

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

  DeviceTransferSearch deviceTransferSearch = DeviceTransferSearch();

  //reset provider data
  void reset() {
    items = null;
    nextPage = true;
    stateCode = null;
    hospital = null;
    building = null;
    floor = null;
    department = null;
    room = "";
    startDate = null;
    endDate = 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;

  Hospital hospital;
  Buildings building;
  Floors floor;
  Departments department;
  String room;
  DateTime startDate;
  DateTime endDate;

  /// 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;
    if (items?.isEmpty ?? true) notifyListeners();
    Response response;
    try {
      Map<String, dynamic> body = {};
      body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;
      body.addAll(deviceTransferSearch.toMap());

      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.toSet().toList());
        notifyListeners();
        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<DeviceTransfer> getRequestById({int assetTransferId}) async {
    Response response;
    try {
      response = await ApiManager.instance.get(
        URLs.getAssetTransferById + "?assetTransferId=$assetTransferId",
        enableToastMessage: false,
      );
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return DeviceTransfer.fromJson(json.decode(response.body)["data"]);
      }
      return null;
    } catch (error) {
      print(error);
      return null;
    }
  }

  Future<int> createRequest({
    @required String host,
    @required User user,
    @required DeviceTransfer model,
  }) async {
    Map<String, dynamic> body = {
      "id": 0,
      "assetId": model.device.id ?? "",
      "destSiteId": hospital.id ?? "",
      "destDepartmentId": department.id ?? "",
      "senderSiteId": model.sender.client.id ?? "",
      // "transferNo": 0,
      // "transferCode": "string",
      "destBuildingId": building?.id,
      "destFloorId": floor.id,
      "destRoom": room,
      /////
      "senderBuildingId": model.device.destBuildingId,
      "senderFloorId": model.device.destFloorId,
      "senderDepartmentId": model.device.destDepartmentId,
      "senderRoom": model.device.destRoom,
      if (model?.sender?.attachments?.isNotEmpty ?? false)
        "senderAttachments":
            model?.sender?.attachments?.map((file) => {"attachmentName": _isLocalUrl(file.path) ? ("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}") : file.path})?.toList(),
      // "senderAssignedEmployeeId": "string",
      // "senderMachineStatusId": 0,
      // "senderComment": "string",
      // "senderStartDate": "2023-06-11T09:21:56.453Z",
      // "senderEndDate": "2023-06-11T09:21:56.453Z",
      // "senderWorkingHours": "string",
      // "senderTravelingHours": "string",
      // "senderAttachmentName": "string",
      // "receiverAssignedEmployeeId": "string",
      // "receiverMachineStatusId": 0,
      // "receiverComment": "string",
      // "receiverStartDate": "2023-06-11T09:21:56.453Z",
      // "receiverEndDate": "2023-06-11T09:21:56.453Z",
      // "receiverWorkingHours": "string",
      // "receiverTravelingHours": "string",
      // "receiverAttachmentName": "string"
    };

    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]));
          reset();
          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,
        "senderStartDate": newModel.timer?.startAt?.toIso8601String(),
        "senderEndDate": newModel.timer?.endAt?.toIso8601String(),
        "senderTravelingHours": newModel.travelingHours,
        "senderEngSignature": newModel.engSignature,
        if (newModel?.attachments?.isNotEmpty ?? false)
          "senderAttachments":
              newModel?.attachments?.map((file) => {"attachmentName": _isLocalUrl(file.path) ? ("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}") : file.path})?.toList(),
        "destSiteId": oldModel.receiver.client?.id,
        "destDepartmentId": oldModel.receiver.department?.id,
        "destBuildingId": oldModel.device?.destBuildingId,
        "destFloorId": oldModel.device?.destFloorId,
        "destRoom": oldModel.device?.destRoom,
        "receiverAssignedEmployeeId": oldModel.receiver.userId,
        "receiverMachineStatusId": oldModel.receiver.status.id ?? "",
        "receiverComment": oldModel.receiver.comment,
        "receiverWorkingHours": oldModel.receiver.workingHours,
        "receiverStartDate": oldModel.receiver.timer?.startAt?.toIso8601String(),
        "receiverEndDate": oldModel.receiver.timer?.endAt?.toIso8601String(),
        "receiverTravelingHours": oldModel.receiver?.travelingHours,
        "receiverEngSignature": oldModel.receiver?.engSignature,
        if (oldModel.receiver?.attachments?.isNotEmpty ?? false)
          "receiverAttachments": oldModel.receiver?.attachments
              ?.map((file) => {"attachmentName": _isLocalUrl(file.path) ? ("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}") : file.path})
              ?.toList(),
      });
    } else {
      body.addAll({
        "senderSiteId": oldModel.sender.client.id,
        "senderDepartmentId": oldModel.sender.department.id,
        "senderAssignedEmployeeId": oldModel.sender.userId,
        "senderMachineStatusId": oldModel.sender.status.id,
        "senderComment": oldModel.sender.comment,
        "senderWorkingHours": oldModel.sender.workingHours,
        "senderStartDate": oldModel.sender.timer?.startAt?.toIso8601String(),
        "senderEndDate": oldModel.sender.timer?.endAt?.toIso8601String(),
        "senderTravelingHours": oldModel.sender?.travelingHours,
        "senderEngSignature": oldModel.sender?.engSignature,
        if (oldModel.sender?.attachments?.isNotEmpty ?? false)
          "senderAttachments":
              oldModel.sender?.attachments?.map((file) => {"attachmentName": _isLocalUrl(file.path) ? ("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}") : file.path})?.toList(),
        "destSiteId": newModel.client?.id,
        "destDepartmentId": newModel.department?.id,
        "destBuildingId": oldModel.device?.destBuildingId,
        "destFloorId": oldModel.device?.destFloorId,
        "destRoom": oldModel.device?.destRoom,
        "receiverAssignedEmployeeId": newModel.userId,
        "receiverMachineStatusId": newModel.status?.id ?? "",
        "receiverComment": newModel.comment,
        "receiverWorkingHours": newModel.workingHours,
        "receiverStartDate": newModel.timer?.startAt?.toIso8601String(),
        "receiverEndDate": newModel.timer?.endAt?.toIso8601String(),
        "receiverTravelingHours": newModel.travelingHours,
        "receiverEngSignature": newModel.engSignature,
        if (newModel?.attachments?.isNotEmpty ?? false)
          "receiverAttachments":
              newModel?.attachments?.map((file) => {"attachmentName": _isLocalUrl(file.path) ? ("${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}") : file.path})?.toList(),
      });
    }
    //body.addAll(newModel.toJson(isSender));
    log(body?.toString());
    Response response;
    try {
      response = await ApiManager.instance.put(URLs.updateDeviceTransfer, body: body);

      print(response.body);
      print("${newModel.engSignature}.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;
    }
  }

  bool _isLocalUrl(String url) {
    if (url?.isEmpty != false) return false;
    return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
  }
}
