import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/energy_data_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_total_energy_consumption_param.dart';
import 'package:syncrow_web/pages/analytics/services/total_energy_consumption/total_energy_consumption_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'total_energy_consumption_event.dart';
part 'total_energy_consumption_state.dart';

class TotalEnergyConsumptionBloc
    extends Bloc<TotalEnergyConsumptionEvent, TotalEnergyConsumptionState> {
  TotalEnergyConsumptionBloc(
    this._totalEnergyConsumptionService,
  ) : super(const TotalEnergyConsumptionState()) {
    on<TotalEnergyConsumptionLoadEvent>(_onTotalEnergyConsumptionLoadEvent);
    on<ClearTotalEnergyConsumptionEvent>(_onClearTotalEnergyConsumptionEvent);
  }

  final TotalEnergyConsumptionService _totalEnergyConsumptionService;

  Future<void> _onTotalEnergyConsumptionLoadEvent(
    TotalEnergyConsumptionLoadEvent event,
    Emitter<TotalEnergyConsumptionState> emit,
  ) async {
    try {
      emit(state.copyWith(status: TotalEnergyConsumptionStatus.loading));
      final chartData = await _totalEnergyConsumptionService.load(event.param);
      emit(
        state.copyWith(
          chartData: chartData,
          status: TotalEnergyConsumptionStatus.loaded,
        ),
      );
    } on APIException catch (e) {
      emit(
        state.copyWith(
          errorMessage: e.message,
          status: TotalEnergyConsumptionStatus.failure,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          errorMessage: e.toString(),
          status: TotalEnergyConsumptionStatus.failure,
        ),
      );
    }
  }

  void _onClearTotalEnergyConsumptionEvent(
    ClearTotalEnergyConsumptionEvent event,
    Emitter<TotalEnergyConsumptionState> emit,
  ) async {
    emit(const TotalEnergyConsumptionState());
  }
}
