import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/device_energy_data_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_energy_consumption_per_device_param.dart';
import 'package:syncrow_web/pages/analytics/services/energy_consumption_per_device/energy_consumption_per_device_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'energy_consumption_per_device_event.dart';
part 'energy_consumption_per_device_state.dart';

class EnergyConsumptionPerDeviceBloc
    extends Bloc<EnergyConsumptionPerDeviceEvent, EnergyConsumptionPerDeviceState> {
  EnergyConsumptionPerDeviceBloc(
    this._energyConsumptionPerDeviceService,
  ) : super(const EnergyConsumptionPerDeviceState()) {
    on<LoadEnergyConsumptionPerDeviceEvent>(_onLoadEnergyConsumptionPerDeviceEvent);
    on<ClearEnergyConsumptionPerDeviceEvent>(
        _onClearEnergyConsumptionPerDeviceEvent);
  }

  final EnergyConsumptionPerDeviceService _energyConsumptionPerDeviceService;

  Future<void> _onLoadEnergyConsumptionPerDeviceEvent(
    LoadEnergyConsumptionPerDeviceEvent event,
    Emitter<EnergyConsumptionPerDeviceState> emit,
  ) async {
    emit(state.copyWith(status: EnergyConsumptionPerDeviceStatus.loading));
    try {
      final chartData = await _energyConsumptionPerDeviceService.load(event.param);
      emit(
        state.copyWith(
          status: EnergyConsumptionPerDeviceStatus.loaded,
          chartData: chartData,
        ),
      );
    } on APIException catch (e) {
      emit(
        state.copyWith(
          status: EnergyConsumptionPerDeviceStatus.failure,
          errorMessage: e.message,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: EnergyConsumptionPerDeviceStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onClearEnergyConsumptionPerDeviceEvent(
    ClearEnergyConsumptionPerDeviceEvent event,
    Emitter<EnergyConsumptionPerDeviceState> emit,
  ) async {
    emit(const EnergyConsumptionPerDeviceState());
  }
}
