const ACTIVITY_EVENTS = ["keydown", "click", "scroll"] as const;

export interface ActivityMonitor {
  start: () => void;
  stop: () => void;
  getLastActivityTimestamp: () => number;
}

export class ActivityMonitorImpl implements ActivityMonitor {
  private lastActivityTimestamp = 0;
  private readonly activityHandler = () => {
    this.lastActivityTimestamp = Date.now();
  };

  start = () => {
    for (const e of ACTIVITY_EVENTS) window.addEventListener(e, this.activityHandler);
  };

  stop = () => {
    for (const e of ACTIVITY_EVENTS) window.removeEventListener(e, this.activityHandler);
  };

  getLastActivityTimestamp = () => this.lastActivityTimestamp;
}

export const createActivityMonitor = (): ActivityMonitor => new ActivityMonitorImpl();
