import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart';
import 'package:logger/logger.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/pantry/pentry.dart';
import 'package:test_sa/models/user.dart';
import 'package:test_sa/models/visits/visit.dart';
import 'package:test_sa/models/visits/visits_group.dart';
import 'package:test_sa/models/visits/visits_search.dart';

class RegularVisitsProvider extends ChangeNotifier{

  // number of items call in each request
  final pageItemNumber = 20;

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

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

  VisitsSearch visitsSearch = VisitsSearch();

  /// 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> getVisits ({
    @required String host,
    @required User user,
   // VisitsSearch visitsSearch,
  }) async {
    if(isLoading == true)
      return -2;
    isLoading = true;
    if(visits == null) notifyListeners();
    Response response;
    //userId = 397.toString(); // testing id to view data

    try{
      Map<String,dynamic> body = {};
      body.addAll(visitsSearch.toMap());
      body["pageNumber"] = (visits?.length ?? 0) ~/pageItemNumber +1;
      body["pageSize"] = pageItemNumber;

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

  /// 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> updateGroupOfVisits ({
    @required String host,
    @required User user,
    VisitsGroup group,
  }) async {
    Response response;

    try{
      Map<String,dynamic> body = group.toJson();

      response = await ApiManager.instance.post(
        URLs.getRegularVisits,
        body: body,
      );
      stateCode = response.statusCode;
      if(response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        reset();
        notifyListeners();
      }

      return response.statusCode;
    } catch(error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<Pentry> getPently({String host,User user,int id}) async {
    Response response;
    response = await get(
        Uri.parse("$host${URLs.getPentry}/$id"),
        headers: {
          "Content-Type":"application/json; charset=utf-8"
        }
    );

    Pentry pantry;
    if(response.statusCode >= 200 && response.statusCode < 300) {
      pantry = Pentry.fromMap(json.decode(utf8.decode(response.bodyBytes)));
    }
    return pantry;
  }

  Future<int> updatePentry ({
    @required String host,
    @required User user,
    @required Pentry pentry,
    @required Visit visit,
  }) async {
    try{
      Response response;
      Map<String,dynamic> body = pentry.toMap(visit.id);
      body["id"] = visit.id;
      body["assetId"] = visit.deviceId;
      body["ppmScheduleId"] = visit.ppmScheduleId;
      // body["token"] = user.token;
      // body["vChecklists"]?.addAll({});
      // body["vCalibrationTools"]?.addAll({"visitId": visit.id,});
      // body["vKits"]?.add({"visitId": visit.id,});
      response = await ApiManager.instance.put(
          URLs.updatePentry, body: body
      );

      // response = await post(
      //   Uri.parse(host+URLs.updatePentry + "/${visit.id}"),
      //   body: body,
      // );
      if(response.statusCode >= 200 && response.statusCode < 300) {
        reset();//visit.status = pentry.ppmVisitStatus;
        notifyListeners();
      }
      return response.statusCode;

    } catch(error) {
      return -1;
    }

  }
}