import 'package:didvan/models/enums.dart';
import 'package:didvan/models/overview_data.dart';
import 'package:didvan/models/requests/news.dart';
import 'package:didvan/providers/core.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';

class NewsState extends CoreProvier {
  String search = '';
  String lastSearch = '';
  String? startDate;
  String? endDate;
  int page = 1;
  int lastPage = 0;

  final List<OverviewData> news = [];

  void init() {
    search = '';
    lastSearch = '';
    startDate = null;
    endDate = null;
    Future.delayed(Duration.zero, () {
      getNews(page: 1);
    });
  }

  void resetFilters() {
    startDate = null;
    endDate = null;
    getNews(page: 1);
  }

  Future<void> getNews({
    required int page,
  }) async {
    this.page = page;
    if (this.page == 1) {
      news.clear();
    }
    if (search != '') {
      lastSearch = search;
    }
    lastSearch = search;
    if (page == 1) {
      appState = AppState.busy;
    }
    final service = RequestService(
      RequestHelper.newsOverviews(
        args: NewsRequestArgs(
          page: page,
          startDate: startDate?.split(' ').first,
          endDate: endDate?.split(' ').first,
          search: search == '' ? null : search,
        ),
      ),
    );
    await service.httpGet();
    if (service.isSuccess) {
      lastPage = service.result['lastPage'];
      final newsList = service.result['news'];
      for (var i = 0; i < newsList.length; i++) {
        news.add(OverviewData.fromJson(newsList[i]));
      }
      appState = AppState.idle;
      return;
    }
    appState = AppState.failed;
  }

  Future<void> onMarkChanged(int id, bool value, bool shouldUpdate) async {
    news.firstWhere((element) => element.id == id).marked = value;
    if (shouldUpdate) {
      notifyListeners();
    }
  }

  Future<void> onLikedChanged(int id, bool value, bool shouldUpdate) async {
    news.firstWhere((element) => element.id == id).liked = value;
    if (shouldUpdate) {
      notifyListeners();
    }
  }

  bool get isFiltering => startDate != null || endDate != null;
}
