import { powerMonitor } from 'electron';
import { getMainWindow } from '../window/create-window';

const IDLE_THRESHOLD_SECONDS = 15 * 60; // 15 minutes
const POLL_INTERVAL_MS = 10_000; // Check every 10 seconds

let pollTimer: ReturnType<typeof setInterval> | null = null;
let wasIdle = false;

const IDLE_STATE_CHANGED_CHANNEL = 'idle-state-changed';

export type IdleState = 'active' | 'idle';

/**
 * Starts polling `powerMonitor.getSystemIdleTime()` and notifies the
 * renderer whenever the user transitions between active and idle.
 */
export function startIdleMonitor(): void {
  if (pollTimer)
    return;

  pollTimer = setInterval(() => {
    const idleSeconds = powerMonitor.getSystemIdleTime();
    const isIdle = idleSeconds >= IDLE_THRESHOLD_SECONDS;

    if (isIdle !== wasIdle) {
      wasIdle = isIdle;
      const state: IdleState = isIdle ? 'idle' : 'active';
      const mainWindow = getMainWindow();

      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.send(IDLE_STATE_CHANGED_CHANNEL, state);
      }
    }
  }, POLL_INTERVAL_MS);
}

export function stopIdleMonitor(): void {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
}

export function getIdleState(): IdleState {
  const idleSeconds = powerMonitor.getSystemIdleTime();

  return idleSeconds >= IDLE_THRESHOLD_SECONDS ? 'idle' : 'active';
}
