import 'dart:convert';

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

import '../../../models/device/device.dart';
import '../../../models/user.dart';
import '../../api_routes/urls.dart';

class DevicesProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _devices = null;
    _stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int? _stateCode;

  int? get stateCode => _stateCode;

  List<Device>? _devices;

  List<Device>? get devices => _devices;

  // when categories in-process _loading = true
  // done _loading = true
  // failed _loading = false
  bool? _loading;

  bool? get isLoading => _loading;

  set isLoading(bool? isLoading) {
    _loading = isLoading;
    notifyListeners();
  }

  /// 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> getEquipment({required String host, required User user, required String hospitalId}) async {
    if (_loading == true) {
      return -2;
    }
    _loading = true;
    notifyListeners();
    Response response;
    try {
      response = await get(
        Uri.parse("${host + URLs.getEquipment}?client=$hospitalId"),
        headers: {"Content-Type": "application/json; charset=utf-8"},
      );
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
    _stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // client's request was successfully received
      List equipmentListJson = json.decode(utf8.decode(response.bodyBytes));
      _devices = equipmentListJson.map((device) => Device.fromJson(device)).toList();
    }
    _loading = 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<List<Device>> getDevicesList({
    required String host,
    required User user,
    required String hospitalId,
    String? serialNumber,
    String? number,
  }) async {
    Response response;
    try {
      response = await get(
        Uri.parse("$host${URLs.getEquipment}?client=$hospitalId"
            "${serialNumber?.isEmpty == false ? "&name=$serialNumber" : ""}"
            "${number?.isEmpty == false ? "&number=$number" : ""}"),
      );
      List<Device> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(utf8.decode(response.bodyBytes));
        page = categoriesListJson.map((device) => Device.fromJson(device)).toList();
      }
      return page;
    } catch (error) {
      return [];
    }
  }

  /// 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<List<Device>> getDevicesListBySN({
    required String host,
    required User user,
    required String hospitalId,
    required String sn,
  }) async {
    Response response;
    try {
      response = await get(
        Uri.parse("$host${URLs.getEquipment}?client=$hospitalId${sn.isEmpty ? "" : "&serial_qr=$sn"}"),
      );

      _stateCode = response.statusCode;
      List<Device> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(utf8.decode(response.bodyBytes));
        page = categoriesListJson.map((device) => Device.fromJson(device)).toList();
      }
      return page;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return [];
    }
  }
}
