import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/data/models/event/skill.dart';
import 'package:krow/core/data/models/shift/business_skill_model.dart';
import 'package:krow/core/data/models/shift/department_model.dart';
import 'package:krow/core/entity/position_entity.dart';
import 'package:krow/core/entity/role_schedule_entity.dart';

part 'create_role_event.dart';
part 'create_role_state.dart';

class CreateRoleBloc extends Bloc<CreateRoleEvent, CreateRoleState> {
  CreateRoleBloc()
      : super(CreateRoleState(
          isExpanded: true,
          entity: PositionEntity.empty(),
        )) {
    on<CreateRoleInitEvent>(_onRoleInit);
    on<CreateRoleSelectSkillEvent>(_onRoleSelect);
    on<ExpandRoleEvent>(_onExpandRole);
    on<SetRoleStartTimeEvent>(_onSetRoleStartTime);
    on<SetRoleEndTimeEvent>(_onSetRoleEndTime);
    on<CreateRoleSelectDepartmentEvent>(_onSelectDepartment);
    on<CreateRoleSelectCountEvent>(_onSelectCount);
    on<CreateRoleSetScheduleEvent>(_onSetRoleSchedule);
    on<CreateRoleSelectBreak>(_onSetRoleBreak);
    on<ValidationPositionFailedEvent>(_onValidationFailed);
  }

  FutureOr<void> _onRoleInit(CreateRoleInitEvent event, emit) {
    emit(state.copyWith(entity: event.role));
  }

  FutureOr<void> _onRoleSelect(CreateRoleSelectSkillEvent event, emit) {
    emit(state.copyWith(entity: state.entity.copyWith(businessSkill: event.skill)));
  }

  FutureOr<void> _onExpandRole(event, emit) {
    emit(state.copyWith(isExpanded: !state.isExpanded));
  }

  FutureOr<void> _onSetRoleStartTime(event, emit) {
    emit(state.copyWith(
        entity: state.entity.copyWith(startTime: event.startTime)));
  }

  FutureOr<void> _onSetRoleEndTime(event, emit) {
    emit(state.copyWith(entity: state.entity.copyWith(endTime: event.endTime)));
  }

  FutureOr<void> _onSelectDepartment(
      CreateRoleSelectDepartmentEvent event, emit) {
    emit(state.copyWith(entity: state.entity.copyWith(department: event.item)));
  }

  FutureOr<void> _onSelectCount(CreateRoleSelectCountEvent event, emit) {
    emit(state.copyWith(entity: state.entity.copyWith(count: event.item)));
  }

  FutureOr<void> _onSetRoleSchedule(CreateRoleSetScheduleEvent event, emit) {
    emit(state.copyWith(
        entity: state.entity.copyWith(schedule: event.schedule)));
  }

  FutureOr<void> _onSetRoleBreak(CreateRoleSelectBreak event, emit) {
    emit(state.copyWith(entity: state.entity.copyWith(breakDuration: event.item)));
  }

  FutureOr<void> _onValidationFailed(ValidationPositionFailedEvent event, emit) {
    emit(state.copyWith(validationState: event.validationState));
  }
}
