import { defineStore, acceptHMRUpdate } from 'pinia';
import { socket } from 'boot/socketio';
import type { DeviceCommands } from 'components/models';

import { useSocketStore } from 'stores/socket';



export const useDeviceStore = defineStore('deviceStore', {
  state: () => {
    return {
      deviceConnected: false as boolean,
    };
  },
  getters: {},
  actions: {
    digestUpdate(data: boolean) {
      this.deviceConnected = data;
    },
    deviceControl(command: DeviceCommands, delay: number = 0) {
      const socketStore = useSocketStore();
      const debugLog = socketStore.debugLog;
      let fnctRtn: { sts: string; msg?: string | undefined } = { sts: '', msg: '' };
      if (debugLog) {
        console.log('deviceStore: got command: ', command, ' with delay: ', delay, ' seconds');
      }
      socket.emit(
        'device_control',
        { command: command, delay: delay },
        (response) => {
          console.log(response.command_status, response.command);
          if (response.command_status == 'ERROR') {
            fnctRtn = { sts: 'error', msg: response.message?.toString() };
            throw new Error(response.message);
          } else {
            fnctRtn = { sts: 'OK', msg: response.message?.toString() };
          }
        },
      );
      return fnctRtn;
    }
  }
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useDeviceStore, import.meta.hot));
}
