import '../../../infrastructure/utility_widgets/loadable_hydrated_bloc/loadable_hydrated_bloc.dart';
import '../../../infrastructure/utility_widgets/loadable_hydrated_bloc/loadable_hydrated_bloc_event.dart';
import '../repository/marianum_dates_repository.dart';
import 'marianum_dates_event.dart';
import 'marianum_dates_state.dart';

class MarianumDatesBloc
    extends
        LoadableHydratedBloc<
          MarianumDatesEvent,
          MarianumDatesState,
          MarianumDatesRepository
        > {
  MarianumDatesBloc() {
    on<SetPastEventsVisible>((event, emit) {
      add(
        Emit((state) => state.copyWith(showPastEvents: event.shouldBeVisible)),
      );
    });
  }

  bool showPastEvents() => innerState?.showPastEvents ?? false;

  List<MarianumDate>? getEvents() =>
      innerState?.events
          .where((e) => showPastEvents() || e.end.isAfter(DateTime.now()))
          .toList() ??
      [];

  @override
  MarianumDatesState fromNothing() =>
      const MarianumDatesState(showPastEvents: false, events: []);
  @override
  MarianumDatesState fromStorage(Map<String, dynamic> json) =>
      MarianumDatesState.fromJson(json);
  @override
  Future<void> gatherData() async {
    final events = await repo.getEvents();
    add(DataGathered((state) => state.copyWith(events: events)));
  }

  @override
  MarianumDatesRepository repository() => MarianumDatesRepository();
  @override
  Map<String, dynamic>? toStorage(state) => state.toJson();
}
