import '../../../../../api/marianumconnect/models/mc_holiday.dart';
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/holidays_repository.dart';
import 'holidays_event.dart';
import 'holidays_state.dart';

class HolidaysBloc
    extends
        LoadableHydratedBloc<HolidaysEvent, HolidaysState, HolidaysRepository> {
  HolidaysBloc() {
    on<SetPastHolidaysVisible>((event, emit) {
      add(
        Emit(
          (state) => state.copyWith(showPastHolidays: event.shouldBeVisible),
        ),
      );
    });

    on<DisclaimerDismissed>(
      (event, emit) =>
          add(Emit((state) => state.copyWith(showDisclaimer: false))),
    );
  }

  bool showPastHolidays() => innerState?.showPastHolidays ?? false;
  bool showDisclaimerOnEntry() => innerState?.showDisclaimer ?? false;
  List<McHoliday>? getHolidays() =>
      innerState?.holidays
          .where(
            (element) =>
                showPastHolidays() ||
                element.endDate.isAfter(DateTime.now()),
          )
          .toList() ??
      [];

  @override
  HolidaysState fromNothing() => const HolidaysState(
    showPastHolidays: false,
    holidays: [],
    showDisclaimer: true,
  );
  @override
  HolidaysState fromStorage(Map<String, dynamic> json) =>
      HolidaysState.fromJson(json);
  @override
  Future<void> gatherData() async {
    var holidays = await repo.getHolidays();
    add(DataGathered((state) => state.copyWith(holidays: holidays)));
  }

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