import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../config/app_config.dart';
import '../../../data/services/bridge_service.dart';
import 'camera_event.dart';
import 'camera_state.dart';

class CameraBloc extends Bloc<CameraEvent, CameraState> {
  final BridgeService _bridgeService;
  final AppConfig _config;

  CameraBloc({
    required BridgeService bridgeService,
    required AppConfig config,
  })  : _bridgeService = bridgeService,
        _config = config,
        super(CameraState(availableCameras: config.allCameraIds)) {
    on<SelectCamera>(_onSelectCamera);
    on<ConnectCameraToMonitor>(_onConnectCameraToMonitor);
    on<ClearCameraSelection>(_onClearCameraSelection);
  }

  void _onSelectCamera(
    SelectCamera event,
    Emitter<CameraState> emit,
  ) {
    emit(state.copyWith(selectedCameraId: event.cameraId, error: null));
  }

  Future<void> _onConnectCameraToMonitor(
    ConnectCameraToMonitor event,
    Emitter<CameraState> emit,
  ) async {
    emit(state.copyWith(isConnecting: true, error: null));

    try {
      final success = await _bridgeService.viewerConnectLive(
        event.monitorId,
        event.cameraId,
      );

      if (success) {
        emit(state.copyWith(isConnecting: false));
      } else {
        emit(state.copyWith(
          isConnecting: false,
          error: 'Failed to connect camera ${event.cameraId} to monitor ${event.monitorId}',
        ));
      }
    } catch (e) {
      emit(state.copyWith(
        isConnecting: false,
        error: e.toString(),
      ));
    }
  }

  void _onClearCameraSelection(
    ClearCameraSelection event,
    Emitter<CameraState> emit,
  ) {
    emit(state.copyWith(clearSelection: true, error: null));
  }
}
