import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/event.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/state.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
  final String deviceId;
  late WallSensorModel deviceStatus;
  Timer? _timer;

  WallSensorBloc({required this.deviceId}) : super(WallSensorInitialState()) {
    on<WallSensorInitialEvent>(_fetchWallSensorStatus);
    on<WallSensorChangeValueEvent>(_changeValue);
    on<GetDeviceReportsEvent>(_getDeviceReports);
    on<ShowDescriptionEvent>(_showDescription);
    on<BackToGridViewEvent>(_backToGridView);
  }

  void _fetchWallSensorStatus(
      WallSensorInitialEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingInitialState());
    try {
      var response = await DevicesManagementApi().getDeviceStatus(deviceId);
      deviceStatus = WallSensorModel.fromJson(response.status);
      emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
      // _listenToChanges();
    } catch (e) {
      emit(WallSensorFailedState(error: e.toString()));
      return;
    }
  }

  // _listenToChanges() {
  //   try {
  //     DatabaseReference ref = FirebaseDatabase.instance.ref('device-status/$deviceId');
  //     Stream<DatabaseEvent> stream = ref.onValue;

  //     stream.listen((DatabaseEvent event) {
  //       Map<dynamic, dynamic> usersMap = event.snapshot.value as Map<dynamic, dynamic>;
  //       List<StatusModel> statusList = [];

  //       usersMap['status'].forEach((element) {
  //         statusList.add(StatusModel(code: element['code'], value: element['value']));
  //       });

  //       deviceStatus = WallSensorModel.fromJson(statusList);
  //       add(WallSensorUpdatedEvent());
  //     });
  //   } catch (_) {}
  // }

  void _changeValue(
      WallSensorChangeValueEvent event, Emitter<WallSensorState> emit) async {
    emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
    if (event.code == 'far_detection') {
      deviceStatus.farDetection = event.value;
    } else if (event.code == 'motionless_sensitivity') {
      deviceStatus.motionlessSensitivity = event.value;
    } else if (event.code == 'motion_sensitivity_value') {
      deviceStatus.motionSensitivity = event.value;
    } else if (event.code == 'no_one_time') {
      deviceStatus.noBodyTime = event.value;
    }
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
    await _runDeBouncer(
        deviceId: deviceId, code: event.code, value: event.value);
  }

  _runDeBouncer({
    required String deviceId,
    required String code,
    required dynamic value,
  }) {
    if (_timer != null) {
      _timer!.cancel();
    }
    _timer = Timer(const Duration(seconds: 1), () async {
      try {
        final response = await DevicesManagementApi()
            .deviceControl(deviceId, Status(code: code, value: value));

        if (!response) {
          add(WallSensorInitialEvent());
        }
      } catch (_) {
        await Future.delayed(const Duration(milliseconds: 500));
        add(WallSensorInitialEvent());
      }
    });
  }

  FutureOr<void> _getDeviceReports(
      GetDeviceReportsEvent event, Emitter<WallSensorState> emit) async {
    emit(DeviceReportsLoadingState());

    try {
      await DevicesManagementApi.getDeviceReports(deviceId, event.code)
          .then((value) {
        emit(DeviceReportsState(deviceReport: value, code:event.code));
      });
    } catch (e) {
      emit(DeviceReportsFailedState(error: e.toString()));
      return;
    }
  }

  void _showDescription(
      ShowDescriptionEvent event, Emitter<WallSensorState> emit) {
    emit(WallSensorShowDescriptionState(description: event.description));
  }

  void _backToGridView(
      BackToGridViewEvent event, Emitter<WallSensorState> emit) {
    emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
  }
}
