/**
 * 定时器管理类
 */
import {
  EncryptManager
} from "../encrypt/index.js"
export class TimerManager {
  /**
   * @param timeStep 时间间隔(默认为1000)
   */
  constructor(timeStep = 1000) {
    // 时间间隔(毫秒)
    this._timeStep = timeStep;
    // 是否运行
    this._isRunning = false;
    // 是否暂停
    this._isPaused = false;
    // 定时器id
    this._timer = null;
    // 执行方法对象
    this._funcList = {};
    // 加密类
    this.encryptManager = new EncryptManager();
  }

  /**
   * 添加
   * @param 执行方法
   */
  add = (func, name) => {
    if (!name) {
      name = this.encryptManager.md5(Date.parse(new Date()))
    }
    // this._funcList.push(func);
    this._funcList[name] = func;
    if (this._isRunning || this._isPaused) return;
    this.run();
  }

  /**
   * 开始
   */
  start = () => {
    this._isPaused = false;
    this.run();
  }

  /**
   * 运行
   */
  run = () => {
    this._timer && clearTimeout(this._timer);
    this._timer = null;
    if (this._isPaused) return;
    let funcListValues = Object.values(this._funcList);
    if (funcListValues.length == 0) {
      this._isRunning = false;
      return;
    }

    this._isRunning = true;

    let funcListNames = Object.keys(this._funcList);
    // 遍历方法列表执行添加的方法
    for (let i = 0; i < funcListValues.length; i++) {
      let func = funcListValues[i];
      // console.log(name);

      // 如果有返回值为false则删除
      if (func() === false) {
        let name = funcListNames[i];
        delete this._funcList[name];
      }
      func = null;
    }

    this._timer = setTimeout(this.run, this._timeStep);
  }

  /**
   * 暂停
   */
  stop = () => {
    this._isPaused = true;
  }

  /**
   * 清除所有定时器
   */
  clear = () => {
    this._timer && clearTimeout(this._timer);
    this._timer = null;
    this._isRunning = false;
    this._isPaused = false;
    // this._funcList = [];
    this._funcList = {};
  }

  /**
   * 移除一个定时器任务
   */
  remove = (name) => {
    if (this._funcList.hasOwnProperty(name)) {
      delete this._funcList[name];
    }
  }

  /**
   * 设置一个定时器
   */
  setTimer = ({
    name,
    seconds,
    onChange,
    onComplate
  } = params) => {
    // 移除已经设置的当前定时器
    this.remove(name);
    let count = 0;
    this.add(() => {
      count++;
      if (count >= seconds) {
        this.remove(name);
        if (onComplate && typeof onComplate === "function") {
          onComplate(true)
        }
      } else {
        if (onChange && typeof onChange === "function") {
          onChange({
            outSeconds: count,
            remainSeconds: seconds - count
          });
        }
      }
    }, name)
  }
}