import { layers } from "../../module/views/layers"
import { Module } from "../../module/views/Module"
import { countDown } from "../common/countDown"
import UI from "../UI"
import { dateLeftFormat, padStart } from "../utils/utils"

type TimeObj = {
  t: number
}

export default class CountDownComp extends Module {
  timeoutFn: Array<Function>
  tobj: TimeObj // 倒计时
  iTime: number // 第一次的时间

  get initTime():number {
    return this.iTime
  }

  /**
   * 初始化时间
   * @param t 
   */
  set initTime(t:number) {
    this.iTime = t
    this.tobj = {t}
    this.formatTime(t)
  }

  constructor(t: number) {
    super(t)
  }

  get groupNames(): string[] {
    return ['CountDownComp']
  }

  cdt: FYGE.TextField
  initUi() {
    UI.Sp(this, 'countdown-back.png')

    this.cdt = UI.Txt(this, '0', 30, '#ffffff', FYGE.TEXT_ALIGN.CENTER, 40, 55, 14)
    
    this.initTime = this.data
  }

  /**
   * 添加 Timeout function
   * @param fnc 
   */
  addTimeoutFunc(fnc: Function) {
    (this.timeoutFn || (this.timeoutFn = [])).push(fnc)
  }

  removeTimeoutFunc(fnc: Function) {
    var i = this.timeoutFn.indexOf(fnc)
    if (i == -1) return null;
    this.timeoutFn.splice(i, 1)
  }

  formatTime(n:number) {
    var _t = ((n / 1000) >> 0)
    this.cdt.text = _t + ''
    return _t
  }

  countDown(time: TimeObj, onChange: Function) {
    var tobj = this.tobj = time
    FYGE.Tween.get(this.tobj, {
      onChange: () => {
        onChange(tobj.t)
      }
    })
      .to({t: 0}, time.t)
      .call(() => {
        this.stop()
        this.timeoutFn && this.timeoutFn.forEach(f => f())
      })
    
    return tobj
  }

  stop() {
    FYGE.Tween.removeTweens(this.tobj)
  }

  restart(t?:number) {
    t && (this.initTime = t)
    this.start()
  }

  start() {
    this.countDown(this.tobj, (n:number) => {
      this.formatTime(n)
    })

  }

  destory() {
    this.stop()
    this.timeoutFn.length = 0
    super.destroy()
  }



}