import { globalShortcut } from 'electron';
import log from 'electron-log';
import { settingsStore } from './store';

let registeredShortcuts: string[] = [];

export function registerShortcuts(onOpen: () => void): void {
  // Unregister existing shortcuts first
  unregisterShortcuts();

  const openShortcut = settingsStore.get('openShortcut');

  // Register the Open shortcut
  const registered = globalShortcut.register(openShortcut, () => {
    log.info(`Global shortcut triggered: ${openShortcut}`);
    onOpen();
  });

  if (registered) {
    registeredShortcuts.push(openShortcut);
    log.info(`Global shortcut registered: ${openShortcut}`);
  } else {
    log.error(`Failed to register global shortcut: ${openShortcut}`);
  }

  // Listen for shortcut changes
  settingsStore.settingsChanged$.subscribe(({ key, value }) => {
    if (key === 'openShortcut') {
      log.info(`Open shortcut changed to: ${value}`);
      registerShortcuts(onOpen);
    }
  });
}

export function unregisterShortcuts(): void {
  registeredShortcuts.forEach(shortcut => {
    globalShortcut.unregister(shortcut);
    log.info(`Global shortcut unregistered: ${shortcut}`);
  });
  registeredShortcuts = [];
}

export function unregisterAllShortcuts(): void {
  globalShortcut.unregisterAll();
  registeredShortcuts = [];
  log.info('All global shortcuts unregistered');
}
