import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/new_models/asset_nd_auto_complete_by_dynamic_codes_model.dart';
import 'package:test_sa/models/new_models/users_based_on_search_model.dart';
import 'package:test_sa/models/service_request/spare_parts.dart';

class UserSearchProvider extends ChangeNotifier {
  // number of items call in each request
  final pageItemNumber = 20;

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

  // true if there is next pagein product list and false if not
  bool _nextPage = true;

  bool get nextPage => _nextPage;

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

  List<SparePartsWorkOrders>? get parts => _parts;

  bool _loading = false;

  bool get isLoading => _loading;

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

  Future<List<UsersBasedOnSearchModel>> getUsersBasedOnSearch(int siteId, String query) async {
    late Response response;
    try {
      response = await ApiManager.instance.get(URLs.getUserByRoleValueSiteMobileAutocomplete + "?siteId=$siteId&roleValue=R-7&searchText=$query");
      List<UsersBasedOnSearchModel> page = [];
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List categoriesListJson = json.decode(response.body);
        page = categoriesListJson.map((part) => UsersBasedOnSearchModel.fromJson(part)).toList();
      }
      return page;
    } catch (error) {
      return [];
    }
  }
}
