import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:meta/meta.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/three_g_glass_switch/models/three_gang_glass_switch.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';

part 'three_gang_glass_switch_event.dart';
part 'three_gang_glass_switch_state.dart';

class ThreeGangGlassSwitchBloc
    extends Bloc<ThreeGangGlassSwitchEvent, ThreeGangGlassSwitchState> {
  ThreeGangGlassStatusModel deviceStatus;
  Timer? _timer;

  ThreeGangGlassSwitchBloc({required String deviceId})
      : deviceStatus = ThreeGangGlassStatusModel(
            uuid: deviceId,
            switch1: false,
            countDown1: 0,
            switch2: false,
            countDown2: 0,
            switch3: false,
            countDown3: 0),
        super(ThreeGangGlassSwitchInitial()) {
    on<ThreeGangGlassSwitchFetchDeviceEvent>(_onFetchDeviceStatus);
    on<ThreeGangGlassSwitchControl>(_onControl);
    on<ThreeGangGlassSwitchBatchControl>(_onBatchControl);
    on<ThreeGangGlassSwitchFetchBatchStatusEvent>(_onFetchBatchStatus);
    on<ThreeGangGlassFactoryReset>(_onFactoryReset);
    on<StatusUpdated>(_onStatusUpdated);
  }

  Future<void> _onFetchDeviceStatus(ThreeGangGlassSwitchFetchDeviceEvent event,
      Emitter<ThreeGangGlassSwitchState> emit) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getDeviceStatus(event.deviceId);
      deviceStatus =
          ThreeGangGlassStatusModel.fromJson(event.deviceId, status.status);
      _listenToChanges(event.deviceId);
      emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(ThreeGangGlassSwitchError(e.toString()));
    }
  }

  _listenToChanges(deviceId) {
    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<Status> statusList = [];
        usersMap['status'].forEach((element) {
          statusList
              .add(Status(code: element['code'], value: element['value']));
        });

        deviceStatus = ThreeGangGlassStatusModel.fromJson(
            usersMap['productUuid'], statusList);
        if (!isClosed) {
          add(StatusUpdated(deviceStatus));
        }
      });
    } catch (_) {}
  }

  void _onStatusUpdated(
      StatusUpdated event, Emitter<ThreeGangGlassSwitchState> emit) {
    deviceStatus = event.deviceStatus;
    emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
  }

  Future<void> _onControl(ThreeGangGlassSwitchControl event,
      Emitter<ThreeGangGlassSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);
    emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));

    await _runDebounce(
      deviceId: event.deviceId,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
      isBatch: false,
    );
  }

  Future<void> _onBatchControl(ThreeGangGlassSwitchBatchControl event,
      Emitter<ThreeGangGlassSwitchState> emit) async {
    final oldValue = _getValueByCode(event.code);

    _updateLocalValue(event.code, event.value);
    emit(ThreeGangGlassSwitchBatchStatusLoaded(deviceStatus));

    await _runDebounce(
      deviceId: event.deviceIds,
      code: event.code,
      value: event.value,
      oldValue: oldValue,
      emit: emit,
      isBatch: true,
    );
  }

  Future<void> _onFetchBatchStatus(
      ThreeGangGlassSwitchFetchBatchStatusEvent event,
      Emitter<ThreeGangGlassSwitchState> emit) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final status =
          await DevicesManagementApi().getBatchStatus(event.deviceIds);
      deviceStatus = ThreeGangGlassStatusModel.fromJson(
          event.deviceIds.first, status.status);
      emit(ThreeGangGlassSwitchBatchStatusLoaded(deviceStatus));
    } catch (e) {
      emit(ThreeGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _onFactoryReset(ThreeGangGlassFactoryReset event,
      Emitter<ThreeGangGlassSwitchState> emit) async {
    emit(ThreeGangGlassSwitchLoading());
    try {
      final response = await DevicesManagementApi()
          .factoryReset(event.factoryReset, event.deviceId);
      if (!response) {
        emit(ThreeGangGlassSwitchError('Failed'));
      } else {
        emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
      }
    } catch (e) {
      emit(ThreeGangGlassSwitchError(e.toString()));
    }
  }

  Future<void> _runDebounce({
    required dynamic deviceId,
    required String code,
    required bool value,
    required bool oldValue,
    required Emitter<ThreeGangGlassSwitchState> emit,
    required bool isBatch,
  }) async {
    late String id;
    if (deviceId is List) {
      id = deviceId.first;
    } else {
      id = deviceId;
    }

    if (_timer != null) {
      _timer!.cancel();
    }

    _timer = Timer(const Duration(milliseconds: 500), () async {
      try {
        late bool response;
        if (isBatch) {
          response = await DevicesManagementApi()
              .deviceBatchControl(deviceId, code, value);
        } else {
          response = await DevicesManagementApi()
              .deviceControl(deviceId, Status(code: code, value: value));
        }

        if (!response) {
          _revertValueAndEmit(id, code, oldValue, emit);
        }
      } catch (e) {
        _revertValueAndEmit(id, code, oldValue, emit);
      }
    });
  }

  void _revertValueAndEmit(String deviceId, String code, bool oldValue,
      Emitter<ThreeGangGlassSwitchState> emit) {
    _updateLocalValue(code, oldValue);
    emit(ThreeGangGlassSwitchStatusLoaded(deviceStatus));
  }

  void _updateLocalValue(String code, bool value) {
    if (code == 'switch_1') {
      deviceStatus = deviceStatus.copyWith(switch1: value);
    } else if (code == 'switch_2') {
      deviceStatus = deviceStatus.copyWith(switch2: value);
    } else if (code == 'switch_3') {
      deviceStatus = deviceStatus.copyWith(switch3: value);
    }
  }

  bool _getValueByCode(String code) {
    switch (code) {
      case 'switch_1':
        return deviceStatus.switch1;
      case 'switch_2':
        return deviceStatus.switch2;
      case 'switch_3':
        return deviceStatus.switch3;
      default:
        return false;
    }
  }

  @override
  Future<void> close() {
    _timer?.cancel();
    return super.close();
  }
}
