import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart'; import 'package:syncrow_web/pages/device_managment/sos/models/sos_status_model.dart'; import 'package:syncrow_web/services/devices_mang_api.dart'; part 'sos_device_event.dart'; part 'sos_device_state.dart'; class SosDeviceBloc extends Bloc { SosDeviceBloc() : super(SosDeviceInitial()) { on(_getDeviceStatus); on(_getBatchStatus); on(_getDeviceRecords); on(_getDeviceAutomationRecords); on(_backToSosStatusView); on(_sosFactoryReset); } late SosStatusModel deviceStatus; FutureOr _getDeviceStatus(GetDeviceStatus event, Emitter emit) async { emit(SosDeviceLoadingState()); try { final status = await DevicesManagementApi().getDeviceStatus(event.uuid); deviceStatus = SosStatusModel.fromJson(event.uuid, status.status); emit(SosDeviceLoadedState(deviceStatus)); } catch (e) { emit(SosDeviceErrorState(e.toString())); } } FutureOr _getBatchStatus(GetBatchStatus event, Emitter emit) async { emit(SosDeviceLoadingState()); try { final status = await DevicesManagementApi().getBatchStatus(event.uuids); deviceStatus = SosStatusModel.fromJson(event.uuids.first, status.status); emit(SosDeviceLoadedState(deviceStatus)); } catch (e) { emit(SosDeviceErrorState(e.toString())); } } FutureOr _getDeviceRecords(GetDeviceRecords event, Emitter emit) async { emit(SosReportLoadingState()); try { final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; final DeviceReport records = await DevicesManagementApi.getDeviceReportsByDate(event.uuid, 'sos', from.toString(), to.toString()); emit(SosReportLoadedState(records)); } catch (e) { emit(SosReportErrorState(e.toString())); } } FutureOr _getDeviceAutomationRecords(GetDeviceAutomationRecords event, Emitter emit) async { emit(SosAutomationReportLoadingState()); try { final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch; final to = DateTime.now().millisecondsSinceEpoch; final DeviceReport records = await DevicesManagementApi.getDeviceReportsByDate( event.uuid, 'sos_automation', from.toString(), to.toString()); emit(SosAutomationReportLoadedState(records)); } catch (e) { emit(SosAutomationReportErrorState(e.toString())); } } FutureOr _backToSosStatusView(BackToSosStatusView event, Emitter emit) { emit(SosDeviceLoadedState(deviceStatus)); } FutureOr _sosFactoryReset(SosFactoryReset event, Emitter emit) async { emit(SosDeviceLoadingState()); try { final response = await DevicesManagementApi().factoryReset(event.factoryReset, event.deviceId); if (response) { emit(SosDeviceLoadedState(deviceStatus)); } else { emit(const SosDeviceErrorState('Factory reset failed')); } } catch (e) { emit(SosDeviceErrorState(e.toString())); } } }