export class Timer {
  isRunning: boolean;
  callback: any;
  elapsedTime: number;
  intervalId: any;
  startTime: number;
  isHour: boolean;
  constructor(callback: (timer: string) => void, isHour = false) {
    this.startTime = 0;
    this.elapsedTime = 0;
    this.isRunning = false;
    this.intervalId = null;
    this.callback = callback; // 可选的回调函数
    this.isHour = isHour; // 可选的回调函数
  }

  start() {
    if (!this.isRunning) {
      this.startTime = Date.now() - this.elapsedTime;
      this.isRunning = true;

      // 开始每秒更新
      this.intervalId = setInterval(() => {
        if (this.callback) {
          this.callback(this.getTimeString());
        }
      }, 1000);

      // 立即执行一次回调
      if (this.callback) {
        this.callback(this.getTimeString());
      }
    }
  }

  stop() {
    if (this.isRunning) {
      this.elapsedTime = Date.now() - this.startTime;
      this.isRunning = false;

      // 停止定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
    }
  }

  reset() {
    this.stop();
    this.startTime = 0;
    this.elapsedTime = 0;
  }

  getTimeString() {
    const currentTime = this.isRunning ? Date.now() - this.startTime : this.elapsedTime;
    const totalSeconds = Math.floor(currentTime / 1000);

    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    if (this.isHour) {
      return `${hours.toString().padStart(2, "0")}:${minutes
        .toString()
        .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    }
    // return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
  }

  // 获取总秒数
  getTotalSeconds() {
    const currentTime = this.isRunning ? Date.now() - this.startTime : this.elapsedTime;
    return Math.floor(currentTime / 1000);
  }
}
