import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:krow/core/entity/role_schedule_entity.dart';
import 'package:meta/meta.dart';

part 'role_schedule_dialog_event.dart';
part 'role_schedule_dialog_state.dart';

class RoleScheduleDialogBloc
    extends Bloc<RoleScheduleDialogEvent, RoleScheduleDialogState> {
  RoleScheduleDialogBloc(List<RoleScheduleEntity> schedule)
      : super(RoleScheduleDialogState(schedule: List.from(schedule))) {
    on<TapOnScheduleDayEvent>(_onTapOnScheduleDay);
    on<SetRoleScheduleStartTimeEvent>(_onSetRoleScheduleStartTime);
    on<SetRoleScheduleEndTimeEvent>(_onSetRoleScheduleEndTime);
  }

  FutureOr<void> _onTapOnScheduleDay(TapOnScheduleDayEvent event, emit) {
    if (state.schedule.any((element) => element.dayIndex == event.index)) {
      emit(state.copyWith(
          schedule: state.schedule
              .where((element) => element.dayIndex != event.index)
              .toList()));
    } else {
      var today = DateTime.now();
      var defStartTime = DateTime(today.year, today.month, today.day, 9, 0);
      var defEndTime = DateTime(today.year, today.month, today.day, 18, 0);
      emit(state.copyWith(schedule: [
        ...state.schedule,
        RoleScheduleEntity(
            dayIndex: event.index, startTime: defStartTime, endTime: defEndTime)
      ]));
    }
  }

  FutureOr<void> _onSetRoleScheduleStartTime(event, emit) {
    emit(state.copyWith(
        schedule: state.schedule
            .map((e) => e.dayIndex == event.schedule.dayIndex
                ? e.copyWith(startTime: event.startTime)
                : e)
            .toList()));
  }

  FutureOr<void> _onSetRoleScheduleEndTime(event, emit) {
    emit(state.copyWith(
        schedule: state.schedule
            .map((e) => e.dayIndex == event.schedule.dayIndex
                ? e.copyWith(endTime: event.endTime)
                : e)
            .toList()));
  }
}
