import { powerMonitor, BrowserWindow } from 'electron';
import { IdleStateChannel } from '@ucap-webmessenger/native-electron';
import { setInterval } from 'timers';

export enum IdleType {
  ACTIVE = 'ACT',
  IDLE = 'IDLE'
}

export class IdleChecker {
  private limitSec: number;
  private intervalObject: any;
  private status: IdleType;
  private window: BrowserWindow | null;

  public constructor(window: BrowserWindow, limitedMin?: number) {
    limitedMin = limitedMin || 10;

    this.limitSec = limitedMin * 60;
    this.intervalObject = null;
    this.status = IdleType.ACTIVE;
    this.window = window;
  }

  private doCheckIdle(): void {
    const idle: number = powerMonitor.getSystemIdleTime();
    if (idle > this.limitSec) {
      if (this.status === IdleType.ACTIVE) {
        this.status = IdleType.IDLE;
        // TODO :: USER_STATUS change away
        this.window.webContents.send(IdleStateChannel.Changed, this.status);
      }
    } else {
      if (this.status === IdleType.IDLE) {
        this.status = IdleType.ACTIVE;
        // TODO :: USER_STATUS chage online
        this.window.webContents.send(IdleStateChannel.Changed, this.status);
      }
    }
  }

  public resetIdleTime(limitedMin: number): void {
    limitedMin = limitedMin || 10;

    if (!!this.intervalObject) {
      clearInterval(this.intervalObject);
      this.intervalObject = undefined;
    }
    this.limitSec = limitedMin * 60;

    this.startChecker();
  }

  public startChecker() {
    if (!this.intervalObject) {
      this.intervalObject = setInterval(() => this.doCheckIdle(), 1000);
    }
  }

  public destoryChecker() {
    if (!!this.intervalObject) {
      clearInterval(this.intervalObject);
      this.intervalObject = undefined;
    }
  }
}
