import { defineStore, acceptHMRUpdate } from 'pinia';
import { socket } from 'boot/socketio';
import { useSocketStore } from 'stores/socket';
import { useQuasar } from 'quasar';

import iCloudCodeDialog from 'components/iCloudCodeDialog.vue';

import type { FindMyUpdate, icloudData, iCloudMonitorResponse } from 'components/models';

const $q = useQuasar();


export const useIcloudStore = defineStore('icloudStore', {
  state: () => {
    return {
      icloudMonitor: false as boolean,
      findMyUpdate: null as FindMyUpdate | null | undefined,
      consumerQueue: 0 as number | string | boolean,
      consumerTask: false as boolean | string,
      monitorTask: false as boolean | string,
      monitorEnabled: false as boolean,
      monitorRunning: false as boolean,
    };
  },
  getters: {},
  actions: {
    bindEvents() {
      const socketStore = useSocketStore();
      const debugLog = socketStore.debugLog;
      // fmf_update
      socket.on('fmf_update', (data: FindMyUpdate): void => {
        if (debugLog) {
          console.log('event: fmf_update received: ', data);
        }
        this.findMyUpdate = data;
      });

      // icloud_2fa_request
      socket.on('icloud_2fa_request', (callback) => {
        if (debugLog) {
          console.log('iCloud 2FA Request');
        }
        $q.dialog({
          component: iCloudCodeDialog,
        })
          .onOk((code: number) => {
            if (callback && typeof callback === 'function') {
              callback(code);
            }
          })
          .onCancel(() => {
            if (debugLog) {
              console.log('Dialog cancelled');
            }
          })
          .onDismiss(() => {
            if (debugLog) {
              console.log('Dialog dismissed');
            }
          });
      });
    },
    icloudMonitorControl(command: string) {
      const socketStore = useSocketStore();
      const debugLog = socketStore.debugLog;
      let fnctRtn: { sts: string; msg?: string | undefined } = { sts: '', msg: '' };
      switch (command) {
        case 'start':
          if (debugLog) {
            console.log('socketStore: got command: icloudMonitor start');
          }
          if (this.icloudMonitor) {
            fnctRtn = { sts: 'error', msg: 'iCloud Monitor is already running' };
            throw new Error('iCloud Monitor is already running');
          }
          if (debugLog) {
            console.log('Emitting icloud_monitor_control: start');
          }
          socket.emit(
            'icloud_monitor_control',
            { command: 'start' },
            (response: iCloudMonitorResponse) => {
              fnctRtn.sts = response.command_status;
              if (response.command_status == 'ERROR') {
                if (response.message) {
                  if (debugLog) {
                    console.log(response.message);
                  }
                  fnctRtn.msg = response.message;
                } else {
                  fnctRtn.msg = 'Error';
                }
                throw new Error(fnctRtn.msg);
              } else {
                fnctRtn = { sts: 'OK', msg: 'iCloud Monitor: ' + response.command_status };
                this.icloudMonitor = true;
              }
            },
          );
          break;
        case 'stop':
          if (debugLog) {
            console.log('socketStore: got command: icloudMonitor stop');
          }
          if (!this.icloudMonitor) {
            fnctRtn = { sts: 'error', msg: 'iCloud Monitor is not running' };
            throw new Error('iCloud Monitor is not running');
          }
          if (debugLog) {
            console.log('Emitting icloud_monitor_control: stop');
          }
          socket.emit(
            'icloud_monitor_control',
            { command: 'stop' },
            (response: iCloudMonitorResponse) => {
              fnctRtn.sts = response.command_status;
              if (response.command_status == 'ERROR') {
                if (response.message) {
                  if (debugLog) {
                    console.log(response.message);
                  }
                  fnctRtn.msg = response.message;
                } else {
                  fnctRtn.msg = 'Error';
                }
                throw new Error(fnctRtn.msg);
              } else {
                fnctRtn = { sts: 'OK', msg: 'iCloud Monitor: ' + response.command_status };
                this.icloudMonitor = false;
              }
            },
          );
          break;
        case 'status':
          if (debugLog) {
            console.log('socketStore: got command: icloudMonitor status');
          }
          socket.emit(
            'icloud_monitor_control',
            { command: 'get' },
            (response: iCloudMonitorResponse) => {
              fnctRtn.sts = response.command_status;
              if (response.command_status == 'error') {
                if (response.message) {
                  if (debugLog) {
                    console.log(response.message);
                  }
                  fnctRtn.msg = response.message;
                } else {
                  fnctRtn.msg = 'Error';
                }
                throw new Error(fnctRtn.msg);
              } else {
                fnctRtn = {
                  sts: 'OK',
                  msg: 'iCloud Location Requested',
                };
              }
              this.icloudMonitor = !!(
                response.icloud_monitor_enabled && response.icloud_monitor_running
              );
            },
          );
          break;
        case 'refresh':
          if (debugLog) {
            console.log('socketStore: got command: icloudMonitor refresh');
          }
          socket.emit(
            'icloud_monitor_control',
            { command: 'status' },
            (response: iCloudMonitorResponse) => {
              fnctRtn.sts = response.command_status;
              if (response.command_status == 'ERROR') {
                if (response.message) {
                  if (debugLog) {
                    console.log(response.message);
                  }
                  fnctRtn.msg = response.message;
                } else {
                  fnctRtn.msg = 'Error';
                }
                throw new Error(fnctRtn.msg);
              } else {
                fnctRtn = {
                  sts: 'OK',
                  msg:
                    'iCloud Monitor Enabled: ' +
                    response.icloud_monitor_enabled +
                    'iCloud Monitor Running: ' +
                    response.icloud_monitor_running,
                };
              }
              this.icloudMonitor = !!(
                response.icloud_monitor_enabled && response.icloud_monitor_running
              );
            },
          );
          break;
        default:
          fnctRtn = { sts: 'error', msg: 'Invalid command' };
          throw new Error('Invalid command');
      }
      return fnctRtn;
    },
    digestUpdate(data: icloudData) {
      this.icloudMonitor = data.monitor_running;
      this.consumerQueue= data.consumer_queue;
      this.consumerTask = data.consumer_task;
      this.monitorEnabled = data.monitor_enabled;
      this.monitorTask = data.monitor_task;
      this.monitorRunning = data.monitor_running;
    }
  },
});

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