import 'package:flutter/material.dart';
import 'package:initial_folder/models/my_course_model.dart';
import 'package:initial_folder/services/course_service.dart';

enum ResultState { Loading, NoData, HasData, Error }

enum SearchResultState { Loading, NoData, HasData, Error }

class MyCourseProvider with ChangeNotifier {
  final CourseService courseService;
  MyCourseProvider({required this.courseService}) {
    getMyCourse();
  }
  MyCourseModel? _myCourseModel;
  MyCourseModel? _searchCourseModel;
  ResultState? _state;
  SearchResultState? _searchResultState;
  String _message = '';

  MyCourseModel? get result => _myCourseModel;
  MyCourseModel? get searchResult => _searchCourseModel;
  ResultState? get state => _state;
  SearchResultState? get searchResultState => _searchResultState;

  String get message => _message;

  set myCourse(MyCourseModel myCourse) {
    _myCourseModel = myCourse;
    notifyListeners();
  }

  Future<dynamic> getMyCourse() async {
    try {
      _state = ResultState.Loading;
      notifyListeners();
      MyCourseModel myCourse = await courseService.getMyCourse();

      if (myCourse.data[0].isEmpty) {
        _state = ResultState.NoData;
        notifyListeners();
        return _message = 'Empty Data';
      } else {
        _state = ResultState.HasData;
        notifyListeners();
        return _myCourseModel = myCourse;
      }
    } catch (e) {
      _state = ResultState.Error;
      notifyListeners();
      print('resultstate mycourse eror');
      return _message = 'Error --> $e';
    }
  }

  Future<dynamic> getSearchMyCourse(String courseName) async {
    try {
      _searchResultState = SearchResultState.Loading;

      notifyListeners();
      MyCourseModel myCourse =
          await courseService.getSearchMyCourse(courseName);
      if (myCourse.data[0].isEmpty) {
        _searchResultState = SearchResultState.NoData;
        notifyListeners();
        return _message = 'Empty Data';
      } else {
        _searchResultState = SearchResultState.HasData;
        notifyListeners();

        return _searchCourseModel = myCourse;
      }
    } catch (e) {
      _searchResultState = SearchResultState.Error;
      notifyListeners();
      return _message = 'Error --> $e';
    }
  }

  clearSearch() {
    _searchResultState = null;
    Future.delayed(Duration(seconds: 2), () {
      if (_searchCourseModel != null && _searchCourseModel!.data.isNotEmpty) {
        _searchCourseModel!.data[0].clear();
      }
    });
  }
}
