import { EventEmitter } from "events";
import { createInterval, destroyInterval } from "../interval";
import { formatTime } from "./utils";

export interface TimeData {
  time: number;
  formatTime: string;
}

interface TimerEvents {
  timeChange: [{ data: TimeData }];
}

export class Timer extends EventEmitter {
  private intervalId = "";

  private lastTime = 0;

  private lastDuration = 0;

  start = () => {
    this.lastTime = Date.now();
    this.timing();
  };

  pause = () => {
    destroyInterval(this.intervalId);
    this.lastDuration += Date.now() - this.lastTime;
  };

  resume = () => {
    this.start();
  };

  stop = () => {
    destroyInterval(this.intervalId);
    this.intervalId = "";
    this.lastTime = 0;
    this.lastDuration = 0;
  };

  private timing = () => {
    destroyInterval(this.intervalId);

    this.intervalId = createInterval(() => {
      const time = Date.now() - this.lastTime + this.lastDuration;
      this.emit("timeChange", {
        data: {
          time,
          formatTime: formatTime(time),
        },
      });
    }, 1000);
  };
}
