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 {
  final List<OverviewData> bookmarks = [];
  final String type;
  int page = 1;
  int lastPage = 1;

  FilteredBookmarksState(this.type);

  Future<void> getBookmarks({required int page}) async {
    this.page = page;
    String typeString = '';
    if (type == 'video' || type == 'podcast') {
      typeString = 'studios';
    } else if (type == 'news') {
      typeString = type;
    } else {
      typeString = type + 's';
    }
    final service = RequestService(
      RequestHelper.bookmarks(
        type: typeString,
        page: page,
        studioType: type == 'podcast' || type == 'video' ? type : null,
      ),
    );
    await service.httpGet();

    if (service.isSuccess) {
      lastPage = service.result['lastPage'];
      final marks = service.result[typeString];
      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 (type == 'radar') {
      UserProvider.changeRadarMark(id, value);
    } else if (type == 'news') {
      UserProvider.changeNewsMark(id, value);
    } else {
      UserProvider.changeStudioMark(id, value);
    }
    bookmarks.removeWhere((element) => element.id == id);
    notifyListeners();
  }

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