

export default class AnswerLogic {
  constructor(sessionId, param) {
    this.sessionId = sessionId;
    this.complieteQueue = [];
    this.pendingQueue = [];
    this.current;
    this.runing = false;

    this.timer = null;
    this.delayTime = 0;

    this.config = param.config || {};
  };

  //会话开始，初始化预设事件（开场白）
  init(queue) {
    if (queue)
      this.pendingQueue = [...queue];
  };
  //开始运行
  start() {
    if (!this.running ) this.next();

  };

  //计算下一个讲解开始时间
  calDelay() {
    let next = null;
    let i = 0;
    while (!next && this.pendingQueue.length > i) {
      if (this.pendingQueue[i].type !== "card") next = this.pendingQueue[i];
      i++;
    }
    const nextDelay = next?.delay || 0;
    const delay =
      (this.current.time || 0) - (this.current.delay || 0) + nextDelay;
    return delay;
  }
  //下一个事件
  next() {
    if (this.delayTime > 50) {
      this.timer = setTimeout(
        () => {
          this.next();
        },
        this.delayTime
      );

      this.delayTime = 0
      return;
    }
    if (this.current) {
      this.complieteQueue.push({ ...this.current });
    }
    if (this.pendingQueue.length > 0) {
      this.running = true;
      this.current = this.pendingQueue.shift();
      // console.log('next :>> ', this.current, this.pendingQueue);
      //输出事件
      this.onOutput(this.current);
      const delay = this.calDelay();
      // console.log('delay :>> ', delay);
      this.timer = setTimeout(
        () => {
          this.next();
        },
        delay < 0 ? 0 : delay
      );
    } else {
      this.running = false;
      this.current = null
    }
  };

  //添加事件到队尾
  addData(event) {
    this.pendingQueue.push(...event);
    if (this.config.start === "auto") {
      setTimeout(() => {
        this.start();
      },0)
    }
    return [...this.pendingQueue]
  }
  //添加事件到队头
  addData2head(event, interrupt = false) {
    if (interrupt && this.current) {
      this.pendingQueue.unshift(this.current)
      clearTimeout(this.timer)
      this.running = false;

    }
    this.pendingQueue.unshift(...event)
    setTimeout(() => {
      this.start();
    })
    return [...this.pendingQueue]
  }

  clear() {
    this.pendingQueue.splice(0);
  }

  delay(timeStamp) {
    this.delayTime = timeStamp;
  }

  //输出事件给表达控制器
  onOutput() {
  };
  //队列改变时返回整个记录
  onChange() {

  };


} 