import 'dart:convert';

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/department.dart';

class DepartmentsProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    departments = null;
    stateCode = null;
  }

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

  // contain user data
  // when user not login or register _user = null
  List<Department>? departments;

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

  /// 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> getDepartment(String host) async {
    if (isLoading == true) return -2;
    isLoading = true;
    notifyListeners();
    late Response response;
    try {
      response = await ApiManager.instance.post(URLs.getDepartments, body: {
        "pageSize": 50,
        // if(title != null && title.isNotEmpty) "name":title,
      });
    } 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
      List listJson = json.decode(response.body)["data"];
      departments = listJson.map((department) => Department.fromJson(department)).toList();
    }
    isLoading = false;
    notifyListeners();
    return response.statusCode;
  }
}
