import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/analytics_device.dart';
import 'package:syncrow_web/pages/analytics/params/get_analytics_devices_param.dart';
import 'package:syncrow_web/pages/analytics/services/analytics_devices/analytics_devices_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'analytics_devices_event.dart';
part 'analytics_devices_state.dart';

class AnalyticsDevicesBloc
    extends Bloc<AnalyticsDevicesEvent, AnalyticsDevicesState> {
  AnalyticsDevicesBloc(
    this._analyticsDevicesService,
  ) : super(const AnalyticsDevicesState()) {
    on<LoadAnalyticsDevicesEvent>(_onLoadAnalyticsDevices);
    on<SelectAnalyticsDeviceEvent>(_onSelectAnalyticsDevice);
    on<ClearAnalyticsDeviceEvent>(_onClearAnalyticsDevice);
  }
  final AnalyticsDevicesService _analyticsDevicesService;

  Future<void> _onLoadAnalyticsDevices(
    LoadAnalyticsDevicesEvent event,
    Emitter<AnalyticsDevicesState> emit,
  ) async {
    emit(const AnalyticsDevicesState(status: AnalyticsDevicesStatus.loading));

    try {
      final devices = await _analyticsDevicesService.getDevices(event.param);
      emit(
        AnalyticsDevicesState(
          status: AnalyticsDevicesStatus.loaded,
          devices: devices,
          selectedDevice: devices.firstOrNull,
        ),
      );
      if (devices.isNotEmpty) {
        event.onSuccess(devices.first);
      }
    } on APIException catch (e) {
      emit(
        AnalyticsDevicesState(
          status: AnalyticsDevicesStatus.failure,
          errorMessage: e.message,
        ),
      );
    } catch (e) {
      emit(
        AnalyticsDevicesState(
          status: AnalyticsDevicesStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onSelectAnalyticsDevice(
    SelectAnalyticsDeviceEvent event,
    Emitter<AnalyticsDevicesState> emit,
  ) {
    emit(
      AnalyticsDevicesState(
        selectedDevice: event.device,
        devices: state.devices,
        errorMessage: state.errorMessage,
        status: state.status,
      ),
    );
  }

  void _onClearAnalyticsDevice(
    ClearAnalyticsDeviceEvent event,
    Emitter<AnalyticsDevicesState> emit,
  ) {
    emit(const AnalyticsDevicesState());
  }
}
