import 'package:didvan/models/enums.dart';
import 'package:didvan/models/overview_data.dart';
import 'package:didvan/providers/core_provider.dart';
import 'package:didvan/providers/user_provider.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';

class BookmarksState extends CoreProvier {
  final List<OverviewData> bookmarks = [];
  String search = '';
  String lastSearch = '';
  int page = 1;
  int lastPage = 1;

  bool get searching => search != '';

  Future<void> getBookmarks({required int page}) async {
    if (search != '') {
      lastSearch = search;
    }
    if (page == 1) {
      bookmarks.clear();
    }
    this.page = page;
    appState = AppState.busy;
    final service =
        RequestService(RequestHelper.bookmarks(page: page, search: search));
    await service.httpGet();

    if (service.isSuccess) {
      lastPage = service.result['lastPage'];
      final marks = service.result['contents'];
      for (var i = 0; i < marks.length; i++) {
        bookmarks.add(OverviewData.fromJson(marks[i]));
      }
      appState = AppState.idle;
      return;
    }
    appState = AppState.failed;
  }

  void onMarkChanged(int id, bool value) {
    if (value) return;
    final type = bookmarks.firstWhere((element) => element.id == id).type;
    switch (type) {
      case 'radar':
        UserProvider.changeRadarMark(id, value);
        break;
      case 'news':
        UserProvider.changeNewsMark(id, value);
        break;
      default:
    }
    bookmarks.removeWhere((element) => element.id == id);
    notifyListeners();
  }
}
