import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart';

import '../../../models/gas_refill/gas_refill_model.dart';
import '../../../models/user.dart';
import '../../api_routes/urls.dart';

class GasRefillProvider 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<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,
  }) async {
    if (isLoading == true) {
      return -2;
    }
    isLoading = true;
    Response response;
    try {
      response = await get(
          Uri.parse("$host${URLs.getGasRefill}?uid=${user.id}"
              "&token=${user.token}&page=${(items?.length ?? 0) ~/ pageItemNumber}"),
          headers: {"Content-Type": "application/json; charset=utf-8"});
      stateCode = response.statusCode;
      if (stateCode != null && stateCode! >= 200 && stateCode! < 300) {
        // client's request was successfully received
        List requestsListJson = json.decode(utf8.decode(response.bodyBytes));
        List<GasRefillModel> itemsPage = requestsListJson.map((request) => GasRefillModel.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> createModel({
    required String host,
    required User user,
    required GasRefillModel model,
  }) async {
    Map<String, dynamic> body = {
      "uid": user.id.toString(),
      "token": user.token ?? "",
      "title": model.title ?? "",
      "status": "0", //model.status.value.toString(),
    };

    body["details"] = jsonEncode(model.details
        ?.map((model) => {
              "type": model.type?.id.toString(),
              "size": model.cylinderSize?.id.toString(),
              "requsted_qty": model.requestedQuantity.toString(),
            })
        .toList());

    Response response;
    try {
      response = await post(
        Uri.parse(host + URLs.requestGasRefill),
        body: body,
      );

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        final items = this.items;
        if (items != null) {
          items.insert(0, GasRefillModel.fromJson(json.decode(utf8.decode(response.bodyBytes))[0]));
          notifyListeners();
        }
      }
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }

  Future<int> updateModel({
    required String host,
    required User user,
    required GasRefillModel? oldModel,
    required GasRefillModel newModel,
  }) async {
    Map<String, dynamic> body = {
      "uid": user.id.toString(),
      "token": user.token,
      "title": newModel.title ?? "",
      "status": newModel.status?.id.toString(),
    };

    body["details"] = jsonEncode(newModel.details
        ?.map((model) => {
              "type": model.type?.id.toString(),
              "size": model.cylinderSize?.id.toString(),
              "requsted_qty": model.requestedQuantity.toString(),
              "deliverd_qty": model.deliveredQuantity.toString(),
            })
        .toList());

    Response response;
    try {
      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;
    }
  }
}
