import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/occupacy.dart';
import 'package:syncrow_web/pages/analytics/params/get_occupancy_param.dart';
import 'package:syncrow_web/pages/analytics/services/occupacy/occupacy_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';

part 'occupancy_event.dart';
part 'occupancy_state.dart';

class OccupancyBloc extends Bloc<OccupancyEvent, OccupancyState> {
  OccupancyBloc(this._occupacyService) : super(const OccupancyState()) {
    on<LoadOccupancyEvent>(_onLoadOccupancyEvent);
    on<ClearOccupancyEvent>(_onClearOccupancyEvent);
  }

  final OccupacyService _occupacyService;

  Future<void> _onLoadOccupancyEvent(
    LoadOccupancyEvent event,
    Emitter<OccupancyState> emit,
  ) async {
    emit(state.copyWith(status: OccupancyStatus.loading));
    try {
      final chartData = await _occupacyService.load(event.param);
      emit(state.copyWith(chartData: chartData, status: OccupancyStatus.loaded));
    } on APIException catch (e) {
      emit(state.copyWith(status: OccupancyStatus.failure, errorMessage: e.message));
    } catch (e) {
      emit(state.copyWith(status: OccupancyStatus.failure, errorMessage: '$e'));
    }
  }

  void _onClearOccupancyEvent(
    ClearOccupancyEvent event,
    Emitter<OccupancyState> emit,
  ) {
    emit(const OccupancyState());
  }
}
