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

export const useTunneldStore = defineStore('tunneldStore', {
  state: () => {
    return {
      tunnelConnected: false as boolean,
      tunneldWatcher: false as boolean,
    };
  },
  getters: {},
  actions: {
    digestUpdate(data: boolean) {
      this.tunnelConnected = data;
    },
    tunneldControl(command: TunneldCommands, udid: string = '') {
      const socketStore = useSocketStore();
      const debugLog = socketStore.debugLog;
      let fnctRtn: { sts: string; msg?: string | undefined } = { sts: '', msg: '' };
      if (debugLog) {
        console.log('tunneldStore: got command: ', command);
      }
      let args: {command: TunneldCommands, udid?: string} = {command: command};
      if (udid != '') {
        args = { command: command, udid: udid };
      }
      socket.emit(
        'tunneld_control', args, (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(useTunneldStore, import.meta.hot));
}
