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/gas_refill/gas_refill_model.dart';
import 'package:test_sa/models/hospital.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/models/user.dart';

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

  //reset provider data
  void reset() {
    items = null;
    nextPage = true;
    stateCode = null;
    hospital = null;
    building = null;
    floor = null;
    department = 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<GasRefillModel> 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,
    bool mostRecent,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (items?.isEmpty ?? true) notifyListeners();
    Response response;

    Map<String, dynamic> body = {};
    body["pageNumber"] = (items?.length ?? 0) ~/ pageItemNumber + 1;
    body["pageSize"] = pageItemNumber;
    print("url:${URLs.getGasRefill}:body:$body");

    response = await ApiManager.instance.post(
      URLs.getGasRefill,
      body: body,
    );
    stateCode = response.statusCode;
    if (stateCode >= 200 && stateCode < 300) {
      // client's request was successfully received
      List requestsListJson = json.decode(response.body)["data"];
      List<GasRefillModel> itemsPage = requestsListJson.map((request) => GasRefillModel.fromJson(request)).toList();
      if (mostRecent != null) {
        items = [];
      } else {
        items ??= [];
      }
      items.addAll(itemsPage);
      sortMostRecent(items, mostRecent);
      notifyListeners();
      if (itemsPage.length == pageItemNumber) {
        nextPage = true;
      } else {
        nextPage = false;
      }
    }
    try {
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  void sortMostRecent(List<GasRefillModel> models, bool mostRecent) {
    if (mostRecent != null) {
      models.sort((prev, next) => (mostRecent ?? false) ? next.title.compareTo(prev.title) : prev.title.compareTo(next.title));
    }
  }

  Future<int> createModel({
    @required String host,
    @required User user,
    @required GasRefillModel model,
  }) async {
    Map<String, dynamic> body = {
      "uid": user.id.toString(),
      "token": user.token ?? "",
      "site": hospital?.toMap(),
      "building": {"id": building?.id, "name": building?.name, "value": building?.value},
      "floor": {"id": floor?.id, "name": floor?.name, "value": floor?.value},
      if (expectedDateTime != null) "expectedDate": expectedDateTime?.toIso8601String(),
      if (expectedDateTime != null) "expectedTime": expectedDateTime?.toIso8601String(),
      if (timer?.startAt != null) "startDate": timer.startAt.toIso8601String(),
      if (timer?.startAt != null) "startTime": timer.startAt.toIso8601String(),
      if (timer?.endAt != null) "endDate": timer.endAt.toIso8601String(),
      if (timer?.endAt != null) "endTime": timer.endAt.toIso8601String(),
      "department": {"id": department?.id, "departmentName": department?.name, "departmentCode": "", "ntCode": ""},
      "GazRefillNo": "GR-${DateTime.now().toString().split(" ").first}",
      "status": model.status.toMap(),
    };
    body["gazRefillDetails"] = model.details
        .map((model) => {
              "gasType": model.type.toMap(),
              "cylinderSize": model.cylinderSize.toMap(),
              "cylinderType": model.cylinderType.toMap(),
              "requestedQty": model.requestedQuantity,
            })
        .toList();

    Response response;
    try {
      response = await ApiManager.instance.post(URLs.requestGasRefill, body: body);
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (items != null) {
          reset();
          notifyListeners();
        }
      }
      return response.statusCode;
    } catch (error) {
      print(error);
      return -1;
    }
  }

  Future<int> updateModel({
    @required String host,
    @required User user,
    @required GasRefillModel oldModel,
    @required GasRefillModel newModel,
  }) async {
    Map<String, dynamic> body = {
      "id": newModel.id,
      "gazRefillNo": newModel.title ?? "",
      "status": newModel.status.toMap(),
      "expectedDate": newModel.expectedDate?.toIso8601String(),
      "expectedTime": newModel.expectedDate?.toIso8601String(),
      if (timer?.startAt != null) "startDate": timer.startAt.toIso8601String(),
      if (timer?.startAt != null) "startTime": timer.startAt.toIso8601String(),
      if (timer?.endAt != null) "endDate": timer.endAt.toIso8601String(),
      if (timer?.endAt != null) "endTime": timer.endAt.toIso8601String(),
      // "workingHours": ((endDate?.difference(startDate)?.inMinutes ?? 0) / 60),
      'workingHours': timer.durationInSecond != null ? timer.durationInSecond / 60 / 60 : newModel.workingHours,
      "assignedEmployee": oldModel?.assignedEmployee?.id == null ? null : oldModel?.assignedEmployee?.toJson(),
      "site": hospital?.toMap(),
      "building": building?.toJson(includeFloors: false),
      "floor": floor?.toJson(includeDepartments: false),
      "department": department?.toJson(),
      "engSignature": newModel.signatureEngineer,
      "nurseSignature": newModel.signatureNurse,
    };

    body["gazRefillDetails"] = newModel.details
        .map((model) => {
              "gasType": model.type.toMap(),
              "cylinderSize": model.cylinderSize.toMap(),
              "cylinderType": model.cylinderType.toMap(),
              "requestedQty": model.requestedQuantity,
              "deliverdQty": model.deliveredQuantity,
            })
        .toList();
    log(body.toString());
    return -1;
    // Response response;
    // try {
    //   response = await ApiManager.instance.put(URLs.updateGasRefill, body: body);
    //   // response = await post(
    //   //   Uri.parse("$host${URLs.updateGasRefill}/${newModel.id}"),
    //   //   body: body,
    //   // );
    //
    //   stateCode = response.statusCode;
    //   if (response.statusCode >= 200 && response.statusCode < 300) {
    //     oldModel.fromGasRefillModel(newModel);
    //     notifyListeners();
    //   }
    //   return response.statusCode;
    // } catch (error) {
    //   return -1;
    // }
  }

  Hospital hospital;
  Buildings building;
  Floors floor;
  Departments department;
  DateTime expectedDateTime;
  TimerModel timer;
}
