import { globalShortcut, BrowserWindow } from 'electron'
import log from 'electron-log'

let registeredWin: BrowserWindow | null = null
let shortcutEnabled = false

const handler = () => {
  log.info('Shortcut Alt+Q triggered')
  if (registeredWin) {
    require('./screenshot').startScreenshot(registeredWin)
  }
}

export function registerShortcut(win: BrowserWindow): void {
  registeredWin = win
  if (!shortcutEnabled) {
    globalShortcut.register('Alt+Q', handler)
    shortcutEnabled = true
    log.info('Shortcut Alt+Q registered')
  }
}

export function disableShortcut(): void {
  if (shortcutEnabled) {
    globalShortcut.unregister('Alt+Q')
    shortcutEnabled = false
    log.info('Shortcut Alt+Q disabled')
  }
}

export function enableShortcut(): void {
  if (!shortcutEnabled && registeredWin) {
    globalShortcut.register('Alt+Q', handler)
    shortcutEnabled = true
    log.info('Shortcut Alt+Q re-enabled')
  }
}

export function unregisterShortcut(): void {
  disableShortcut()
  registeredWin = null
}
