import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/occupancy_heat_map_model.dart';
import 'package:syncrow_web/pages/analytics/params/get_occupancy_heat_map_param.dart';
import 'package:syncrow_web/pages/analytics/services/occupancy_heat_map/occupancy_heat_map_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'occupancy_heat_map_event.dart';
part 'occupancy_heat_map_state.dart';

class OccupancyHeatMapBloc
    extends Bloc<OccupancyHeatMapEvent, OccupancyHeatMapState> {
  OccupancyHeatMapBloc(
    this._occupancyHeatMapService,
  ) : super(const OccupancyHeatMapState()) {
    on<LoadOccupancyHeatMapEvent>(_onLoadOccupancyHeatMapEvent);
    on<ClearOccupancyHeatMapEvent>(_onClearOccupancyHeatMapEvent);
  }
  final OccupancyHeatMapService _occupancyHeatMapService;

  Future<void> _onLoadOccupancyHeatMapEvent(
    LoadOccupancyHeatMapEvent event,
    Emitter<OccupancyHeatMapState> emit,
  ) async {
    emit(state.copyWith(status: OccupancyHeatMapStatus.loading));
    try {
      final occupancyHeatMap = await _occupancyHeatMapService.load(event.param);
      emit(
        state.copyWith(
          status: OccupancyHeatMapStatus.loaded,
          heatMapData: occupancyHeatMap,
        ),
      );
    } on APIException catch (e) {
      emit(
        state.copyWith(
          status: OccupancyHeatMapStatus.failure,
          errorMessage: e.message,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: OccupancyHeatMapStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void _onClearOccupancyHeatMapEvent(
    ClearOccupancyHeatMapEvent event,
    Emitter<OccupancyHeatMapState> emit,
  ) {
    emit(const OccupancyHeatMapState());
  }
}
