import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/rbac/rbac_station.dart';
import 'package:unit2/sevices/roles/rbac_operations/station_services.dart';
import '../../../../model/utils/agency.dart';
import '../../../../utils/profile_utilities.dart';
part 'station_event.dart';
part 'station_state.dart';

class StationBloc extends Bloc<StationEvent, StationState> {
  StationBloc() : super(StationInitial()) {
    List<RbacStation> stations = [];
    List<Agency> agencies = [];
    on<GetStations>((event, emit) async {
      emit(StationLoadingState());
      try {
        stations = await RbacStationServices.instance
            .getStations(agencyId: event.agencyId.toString());

        if (agencies.isEmpty) {
          List<Agency> newAgencies =
              await ProfileUtilities.instance.getAgecies();
          agencies = newAgencies;
        }
        emit(StationLoadedState(stations: stations, agencies: agencies));
      } catch (e) {
        emit(StationErrorState(message: e.toString()));
      }
    });
    on<FilterStation>((event, emit)async {
          // emit(StationLoadingState());
         try {
        stations = await RbacStationServices.instance
            .getStations(agencyId: event.agencyId.toString());

        if (agencies.isEmpty) {
          List<Agency> newAgencies =
              await ProfileUtilities.instance.getAgecies();
          agencies = newAgencies;
        }
        emit(StationLoadedState(stations: stations, agencies: agencies));
      } catch (e) {
        emit(StationErrorState(message: e.toString()));
      }
    });
  }
}
