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/ceiling_sensor/bloc/event.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/bloc/state.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/ceiling_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/ceiling_sensor/model/help_description.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

class CeilingSensorBloc extends Bloc<CeilingSensorEvent, CeilingSensorState> {
  final String deviceId;
  late CeilingSensorModel deviceStatus;
  Timer? _timer;

  CeilingSensorBloc({required this.deviceId}) : super(CeilingInitialState()) {
    on<CeilingInitialEvent>(_fetchCeilingSensorStatus);
    on<CeilingChangeValueEvent>(_changeValue);
    on<GetCeilingDeviceReportsEvent>(_getDeviceReports);
    on<ShowCeilingDescriptionEvent>(_showDescription);
    on<BackToCeilingGridViewEvent>(_backToGridView);
  }

  void _fetchCeilingSensorStatus(
      CeilingInitialEvent event, Emitter<CeilingSensorState> emit) async {
    emit(CeilingLoadingInitialState());
    try {
      var response = await DevicesManagementApi().getDeviceStatus(deviceId);
      deviceStatus = CeilingSensorModel.fromJson(response.status);
      emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
      // _listenToChanges();
    } catch (e) {
      emit(CeilingFailedState(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(
      CeilingChangeValueEvent event, Emitter<CeilingSensorState> emit) async {
    emit(CeilingLoadingNewSate(ceilingSensorModel: deviceStatus));
    if (event.code == 'sensitivity') {
      deviceStatus.sensitivity = event.value;
    } else if (event.code == 'none_body_time') {
      deviceStatus.noBodyTime = event.value;
    } else if (event.code == 'moving_max_dis') {
      deviceStatus.maxDistance = event.value;
    } else if (event.code == 'scene') {
      deviceStatus.spaceType = getSpaceType(event.value);
    }
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
    await _runDeBouncer(
        deviceId: deviceId, code: event.code, value: event.value, emit: emit);
  }

  _runDeBouncer({
    required String deviceId,
    required String code,
    required dynamic value,
    required Emitter<CeilingSensorState> emit,
  }) {
    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(CeilingInitialEvent());
        }
        if (response == true && code == 'scene') {
          emit(CeilingLoadingInitialState());
          await Future.delayed(const Duration(seconds: 1));
          add(CeilingInitialEvent());
        }
      } catch (_) {
        await Future.delayed(const Duration(milliseconds: 500));
        add(CeilingInitialEvent());
      }
    });
  }

  FutureOr<void> _getDeviceReports(GetCeilingDeviceReportsEvent event,
      Emitter<CeilingSensorState> emit) async {
    if (event.code.isEmpty) {
      emit(ShowCeilingDescriptionState(description: reportString));
      return;
    } else {
      emit(CeilingReportsLoadingState());

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

  void _showDescription(
      ShowCeilingDescriptionEvent event, Emitter<CeilingSensorState> emit) {
    emit(ShowCeilingDescriptionState(description: event.description));
  }

  void _backToGridView(
      BackToCeilingGridViewEvent event, Emitter<CeilingSensorState> emit) {
    emit(CeilingUpdateState(ceilingSensorModel: deviceStatus));
  }
}
