import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/device_location_info.dart';
import 'package:syncrow_web/pages/analytics/params/get_device_location_data_param.dart';
import 'package:syncrow_web/pages/analytics/services/device_location/device_location_service.dart';

part 'device_location_event.dart';
part 'device_location_state.dart';

class DeviceLocationBloc extends Bloc<DeviceLocationEvent, DeviceLocationState> {
  DeviceLocationBloc(
    this._deviceLocationService,
  ) : super(const DeviceLocationState()) {
    on<LoadDeviceLocationEvent>(_onLoadDeviceLocation);
    on<ClearDeviceLocationEvent>(_onClearDeviceLocation);
  }

  final DeviceLocationService _deviceLocationService;

  Future<void> _onLoadDeviceLocation(
    LoadDeviceLocationEvent event,
    Emitter<DeviceLocationState> emit,
  ) async {
    emit(const DeviceLocationState(status: DeviceLocationStatus.loading));

    try {
      final locationInfo = await _deviceLocationService.get(event.param);
      emit(
        DeviceLocationState(
          status: DeviceLocationStatus.success,
          locationInfo: locationInfo,
        ),
      );
    } catch (e) {
      emit(
        DeviceLocationState(
          status: DeviceLocationStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onClearDeviceLocation(
    ClearDeviceLocationEvent event,
    Emitter<DeviceLocationState> emit,
  ) {
    emit(const DeviceLocationState());
  }
}
