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 FilteredBookmarksState extends CoreProvier {
  String search = '';
  String lastSearch = '';
  final List<OverviewData> bookmarks = [];
  final String type;

  FilteredBookmarksState(this.type);

  bool get searching => search != '';

  Future<void> getBookmarks() async {
    if (search != '') {
      lastSearch = search;
    }
    appState = AppState.busy;
    final service = RequestService(
      RequestHelper.bookmarks(type: type == 'news' ? type : type + 's'),
    );
    await service.httpGet();

    if (service.isSuccess) {
      final marks = service.result[type != 'news' ? type + 's' : type];
      bookmarks.clear();
      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) {
    switch (type) {
      case 'radar':
        UserProvider.changeRadarMark(id, value);
        break;
      case 'news':
        UserProvider.changeNewsMark(id, value);
        break;
      default:
    }
    bookmarks.removeWhere((element) => element.id == id);
    notifyListeners();
  }

  void onCommentsChanged(int id, int value) {
    bookmarks.firstWhere((radar) => radar.id == id).comments = value;
    notifyListeners();
  }
}
