import Dom from '../../libs/dom'
import Widget from '../widget'

function formatTime(fmt) {
  let now = new Date()
  let weekday = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六'
  ]
  var o = {
    'M+': now.getMonth() + 1, //月份
    'd+': now.getDate(), //日
    'H+': now.getHours(), //小时
    'm+': now.getMinutes(), //分
    's+': now.getSeconds(), //秒
    'q+': Math.floor((now.getMonth() + 3) / 3), //季度
    S: ('000' + now.getMilliseconds()).substr(
      ('' + now.getMilliseconds()).length
    ), //毫秒
    W: weekday[now.getDay()]
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (now.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}
class Timer extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this._container = Dom.createElement('div', 'time-container comp', this.el)
    this.timer = null
    this.setLayout()
    this.setPaint()
  }

  setPaint() {
    this.setListener()
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    this._container.innerHTML = ''
    let newPaint = this._mergePaint()
    Dom.css(this._container, {
      fontSize: newPaint.fontSize + 'px',
      fontWeight: newPaint.bold ? 'bold' : 'normal',
      color: newPaint.fontColor,
      fontFamily: newPaint.fontFamily
    })
    let interval = Number(newPaint.interval) * 1000
    let span = Dom.createElement('span', '', this._container)
    let format = newPaint.timeFormat
    span.innerHTML = formatTime(format)
    this.timer = setInterval(() => {
      span.textContent = formatTime(format)
    }, interval)
  }

  remove() {
    clearInterval(this.timer)
    this.timer = null
    super.remove()
  }
}

export default Timer
