import 'package:bloc/bloc.dart';
import 'package:krow/core/data/models/event/event_model.dart';
import 'package:krow/core/entity/event_entity.dart';
import 'package:meta/meta.dart';

part 'date_selector_event.dart';
part 'date_selector_state.dart';

class DateSelectorBloc extends Bloc<DateSelectorEvent, DateSelectorState> {
  DateSelectorBloc() : super(const DateSelectorState()) {
    on<DateSelectorEventInit>(_onInit);
    on<DateSelectorEventChangeStartDate>(_onChangeStartDate);
    on<DateSelectorEventChangeEndDate>(_onChangeEndDate);
    on<DateSelectorEventRepeatType>(_onChangeRepeatType);
    on<DateSelectorEventEndType>(_onChangeEndType);
    on<DateSelectorEventChangeEndsAfterWeeks>(_onChangeEndsAfterWeeks);
  }

  void _onInit(DateSelectorEventInit event, Emitter<DateSelectorState> emit) {
    if (event.eventModel != null) {
      emit(state.copyWith(
        startDate: DateTime.parse(event.eventModel!.date),
      ));
      return;
    } else {
      emit(state.copyWith(
        recurringType: event.recurringType,
        endDateType: EndDateType.endDate,
        repeatType: EventRepeatType.daily,
      ));
    }
  }

  void _onChangeStartDate(
      DateSelectorEventChangeStartDate event, Emitter<DateSelectorState> emit) {
    if (event.startDate == state.startDate) return;

    event.entity.startDate = event.startDate;

    emit(state.copyWith(
      startDate: event.startDate,
    ));
  }

  void _onChangeEndDate(
      DateSelectorEventChangeEndDate event, Emitter<DateSelectorState> emit) {
    if (event.endDate == state.startDate) return;
    event.entity.endDate = event.endDate;

    emit(state.copyWith(
      endDate: event.endDate,
    ));
  }

  void _onChangeRepeatType(
      DateSelectorEventRepeatType event, Emitter<DateSelectorState> emit) {
    if (event.type == state.repeatType) return;
    emit(state.copyWith(
      repeatType: event.type,
    ));
  }

  void _onChangeEndType(
      DateSelectorEventEndType event, Emitter<DateSelectorState> emit) {
    if (event.type == state.endDateType) return;
    emit(state.copyWith(
      endDateType: event.type,
    ));
  }

  void _onChangeEndsAfterWeeks(DateSelectorEventChangeEndsAfterWeeks event,
      Emitter<DateSelectorState> emit) {
    if (event.weeks == state.andsAfterWeeksCount) return;
    emit(state.copyWith(
      andsAfterWeeksCount: event.weeks,
    ));
  }
}
