import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/course_model.dart';
import 'package:initial_folder/services/search_service.dart';

enum ResultState { loading, noData, hasData, error }

class SearchProvider with ChangeNotifier {
  final SearchService searchService;
  SearchProvider({required this.searchService});

  ResultState? _state;
  String _message = '';
  List<CourseModel> _searchCourse = [];
  String _search = '';
  String _searchFilter = '';

  ResultState? get state => _state;
  List<CourseModel> get result => _searchCourse;
  String get message => _message;
  String get search => _search;
  String get searchFilter => _searchFilter;
  String get searchText => _search;
  String get searchTextFilter => _searchFilter;

  void resetState() {
    _state = null;
  }

  set searchText(String text) {
    _search = text;
    notifyListeners();
  }

  set searchTextFilter(String text) {
    _searchFilter = text;
    notifyListeners();
  }

  void clearSearchBox() {
    _search = '';
    notifyListeners();
  }

  initSearchCourse({
    String price = '',
    String level = '',
    String language = '',
    String rating = '',
  }) async {
    try {
      _state = ResultState.loading;

      List<CourseModel> course = await searchService.filter(
        price: price,
        level: level,
        language: language,
        rating: rating,
        keyword: _search,
      );

      if (course.isEmpty) {
        _state = ResultState.noData;
        notifyListeners();
        _message = 'Empty Data';
      } else {
        _state = ResultState.hasData;

        _searchCourse = course;
      }
    } catch (e) {
      _state = ResultState.error;

      _message = 'Error --> $e';
    }
    notifyListeners();
  }

  Future<dynamic> searchCourse(judul) async {
    try {
      _state = ResultState.loading;
      notifyListeners();
      List<CourseModel> course = await searchService.search(judul);

      if (course.isEmpty) {
        _state = ResultState.noData;
        notifyListeners();
        return _message = 'Empty Data';
      } else {
        _state = ResultState.hasData;
        notifyListeners();
        return _searchCourse = course;
      }
    } catch (e) {
      _state = ResultState.error;
      notifyListeners();
      return _message = 'Error --> $e';
    }
  }
}
