import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/phases_energy_consumption.dart';
import 'package:syncrow_web/pages/analytics/params/get_energy_consumption_by_phases_param.dart';
import 'package:syncrow_web/pages/analytics/services/energy_consumption_by_phases/energy_consumption_by_phases_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'energy_consumption_by_phases_event.dart';
part 'energy_consumption_by_phases_state.dart';

class EnergyConsumptionByPhasesBloc
    extends Bloc<EnergyConsumptionByPhasesEvent, EnergyConsumptionByPhasesState> {
  EnergyConsumptionByPhasesBloc(
    this._energyConsumptionByPhasesService,
  ) : super(const EnergyConsumptionByPhasesState()) {
    on<LoadEnergyConsumptionByPhasesEvent>(_onLoadEnergyConsumptionByPhasesEvent);
    on<ClearEnergyConsumptionByPhasesEvent>(_onClearEnergyConsumptionByPhasesEvent);
  }

  final EnergyConsumptionByPhasesService _energyConsumptionByPhasesService;

  Future<void> _onLoadEnergyConsumptionByPhasesEvent(
    LoadEnergyConsumptionByPhasesEvent event,
    Emitter<EnergyConsumptionByPhasesState> emit,
  ) async {
    emit(state.copyWith(status: EnergyConsumptionByPhasesStatus.loading));
    try {
      final chartData = await _energyConsumptionByPhasesService.load(event.param);
      emit(
        state.copyWith(
          status: EnergyConsumptionByPhasesStatus.loaded,
          chartData: chartData,
        ),
      );
    } on APIException catch (e) {
      emit(
        state.copyWith(
          status: EnergyConsumptionByPhasesStatus.failure,
          errorMessage: e.message,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: EnergyConsumptionByPhasesStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onClearEnergyConsumptionByPhasesEvent(
    ClearEnergyConsumptionByPhasesEvent event,
    Emitter<EnergyConsumptionByPhasesState> emit,
  ) async {
    emit(const EnergyConsumptionByPhasesState());
  }
}
