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/modules/cleaner_module/models/task_type.dart';

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

  // state code of current request to define error message
  int? _stateCode;
  int? get stateCode => _stateCode;

  // contain task types data
  List<TaskType>? _taskTypes;
  List<TaskType>? get taskTypes => _taskTypes;

  // loading state
  bool _loading = false;
  bool get isLoading => _loading;

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

  /// Get task types
  Future<int> getTaskTypes() async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      response = await ApiManager.instance.get(URLs.getTaskType);
      _stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List taskTypesListJson = json.decode(response.body)["data"];
        _taskTypes = taskTypesListJson.map((taskType) => TaskType.fromJson(taskType)).toList();
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  /// Get task types list directly without provider state
  Future<List<TaskType>> getTaskTypesList() async {
    Response response;
    try {
      response = await ApiManager.instance.get(URLs.getTaskType);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        List taskTypesListJson = json.decode(response.body)["data"];
        return taskTypesListJson.map((taskType) => TaskType.fromJson(taskType)).toList();
      }
      return [];
    } catch (error) {
      return [];
    }
  }
}

