import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/gateway_bloc/gateway_event.dart';
import 'package:syncrow_app/features/devices/bloc/gateway_bloc/gateway_state.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/services/api/devices_api.dart';

class GatewayBloc extends Bloc<GatewayEvent, GatewayState> {
  GatewayBloc() : super(GatewayInitialState()) {
    on<GatewayInitial>(_fetchDevices);
  }

  void _fetchDevices(GatewayInitial event, Emitter<GatewayState> emit) async {
    emit(GatewayLoadingState());
    try {
      List<DeviceModel> devicesList = await DevicesAPI.getDevicesByGatewayId(event.gatewayId);

      emit(UpdateGatewayState(list: devicesList));
    } catch (e) {
      emit(ErrorState(message: e.toString()));
      return;
    }
  }
}
