import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/visitor_password/model/device_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

part 'gate_way_event.dart';
part 'gate_way_state.dart';

class GateWayBloc extends Bloc<GateWayEvent, GateWayState> {
  GateWayBloc() : super(GateWayInitial()) {
    on<GateWayFetch>((event, emit) {});
    on<GatWayById>(_getGatWayById);
    on<GateWayFactoryReset>(_onFactoryReset);
  }

  FutureOr<void> _getGatWayById(GatWayById event, Emitter<GateWayState> emit) async {
    emit(GatewayLoadingState());
    try {
      List<DeviceModel> devicesList = await DevicesManagementApi.getDevicesByGatewayId(event.getWayId);

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

  FutureOr<void> _onFactoryReset(GateWayFactoryReset event, Emitter<GateWayState> emit) async {
    emit(GatewayLoadingState());
    try {
      final response = await DevicesManagementApi().factoryReset(
        event.factoryReset,
        event.deviceId,
      );
      if (!response) {
        emit(const ErrorState(message: 'Failed'));
      } else {
        add(GatWayById(event.deviceId));
      }
    } catch (e) {
      emit(ErrorState(message: e.toString()));
    }
  }
}
