import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/services/power_clamp_info/power_clamp_info_service.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/power_clamp/models/power_clamp_model.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'power_clamp_info_event.dart';
part 'power_clamp_info_state.dart';

class PowerClampInfoBloc extends Bloc<PowerClampInfoEvent, PowerClampInfoState> {
  PowerClampInfoBloc(
    this._powerClampInfoService,
  ) : super(const PowerClampInfoState()) {
    on<LoadPowerClampInfoEvent>(_onLoadPowerClampInfoEvent);
    on<UpdatePowerClampStatusEvent>(_onUpdatePowerClampStatusEvent);
    on<ClearPowerClampInfoEvent>(_onClearPowerClampInfoEvent);
  }

  final PowerClampInfoService _powerClampInfoService;

  Future<void> _onLoadPowerClampInfoEvent(
    LoadPowerClampInfoEvent event,
    Emitter<PowerClampInfoState> emit,
  ) async {
    emit(state.copyWith(status: PowerClampInfoStatus.loading));
    try {
      final powerClampModel = await _powerClampInfoService.getInfo(event.deviceId);
      emit(
        state.copyWith(
          status: PowerClampInfoStatus.loaded,
          powerClampModel: powerClampModel,
        ),
      );
    } on APIException catch (e) {
      emit(
        state.copyWith(
          status: PowerClampInfoStatus.error,
          errorMessage: e.message,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: PowerClampInfoStatus.error,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onUpdatePowerClampStatusEvent(
    UpdatePowerClampStatusEvent event,
    Emitter<PowerClampInfoState> emit,
  ) async {
    final currentModel = state.powerClampModel;
    if (currentModel == null) return;

    final updatedStatus = PowerStatus.fromStatusList(event.statusList);
    final updatedModel = currentModel.copyWith(statusPower: updatedStatus);

    emit(state.copyWith(powerClampModel: updatedModel));
  }

  void _onClearPowerClampInfoEvent(
    ClearPowerClampInfoEvent event,
    Emitter<PowerClampInfoState> emit,
  ) {
    emit(const PowerClampInfoState());
  }
}
