import 'dart:convert';

import 'package:flutter/material.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/employee.dart';

import '../../../../../models/new_models/assigned_employee.dart';
import '../../../../../models/new_models/assistant_employee.dart';

class ServiceReportAssistantsEmployeeProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _assistantEmployees = null;
    _loading = false; // Set to false initially
    _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;

  set stateCode(int? statusCode) => _stateCode = statusCode;

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

  List<AssistantEmployees>? get assistantEmployees => _assistantEmployees;

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

  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> getAssistantEmployees(num assetId) async {
    if (_loading) return -2;
    _loading = true;
    notifyListeners();
    try {final response = await ApiManager.instance.get("${URLs.getEngineers}&assetId=$assetId");
    _stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      final usersListJson = json.decode(response.body) as List;
      _assistantEmployees = usersListJson
          .map((type) => Employee.fromJson(type))
          .map((e) => AssistantEmployees(user: AssignedEmployee(id: e.id, name: e.name)))
          .toList();
      _assistantEmployees?.insert(0, AssistantEmployees(id: -1, user: AssignedEmployee(id: "-1", name: "-- Select --")));
    }
    _loading = false;
    notifyListeners();
    return response.statusCode;
    } catch (error) {
      _loading = false;
      _stateCode = -1;
      notifyListeners();
      return -1;
    }
  }
}