import electron from 'electron';
const { globalShortcut } = electron;

export interface HotkeyBinding {
  accelerator: string;
  onTrigger: () => void;
}

export class HotkeyService {
  private registered: string[] = [];

  register(binding: HotkeyBinding): { ok: boolean; reason?: string } {
    const accel = binding.accelerator;
    if (globalShortcut.isRegistered(accel)) {
      return { ok: false, reason: `${accel} already registered by another app` };
    }
    const ok = globalShortcut.register(accel, binding.onTrigger);
    if (!ok) return { ok: false, reason: `failed to register ${accel}` };
    this.registered.push(accel);
    return { ok: true };
  }

  unregisterAll(): void {
    for (const a of this.registered) globalShortcut.unregister(a);
    this.registered = [];
  }
}
