import Dom from '../../libs/dom'
import Widget from '../widget'
import CountUp from 'countup.js'

class Metric extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this._container = Dom.createElement('div', 'metric-container comp', this.el)
    this.value = 0
  }

  setPaint() {
    this.setListener()
    this._container.innerHTML = ''
    let newPaint = this._mergePaint()
    let value = 0
    if (Number.isNaN(+newPaint.number.value)) {
      if (this.originalData && this.originalData.length) {
        value = Number(this.originalData[0][newPaint.number.value]) || 0
      }
    } else {
      value = Number(newPaint.number.value) || 0
    }
    Dom.css(this._container, {
      fontFamily: newPaint.common.fontFamily,
      textAlign: newPaint.common.textAlign
    })
    let prefix = Dom.createElement('div', 'prefix', this._container)
    prefix.innerText = newPaint.prefix.content
    Dom.css(prefix, {
      display: newPaint.common.orient === 'vertical' ? 'block' : 'inline',
      color: newPaint.prefix.fontColor,
      fontSize: newPaint.prefix.fontSize + 'px',
      fontWeight: newPaint.prefix.bold ? 'bold' : 'normal',
      lineHeight: newPaint.prefix.lineHeight + 'em'
    })

    let decimalDigits = newPaint.number.decimalDigits
    let commaSeparator = newPaint.number.commaSeparator
    let number = Dom.createElement('div', 'number', this._container)
    Dom.css(number, {
      display: newPaint.common.orient === 'vertical' ? 'block' : 'inline',
      fontWeight: newPaint.number.bold ? 'bold' : 'normal',
      fontSize: newPaint.number.fontSize + 'px',
      color: newPaint.number.fontColor,
      lineHeight: newPaint.number.lineHeight + 'em'
    })
    let options = {
      useEasing: true,
      useGrouping: true,
      separator: commaSeparator ? ',' : ''
    }
    let countup = new CountUp(
      number,
      this.value,
      value,
      decimalDigits,
      1,
      options
    )

    let suffix = Dom.createElement('div', 'suffix', this._container)
    suffix.innerText = newPaint.suffix.content
    Dom.css(suffix, {
      display: newPaint.common.orient === 'vertical' ? 'block' : 'inline',
      color: newPaint.suffix.fontColor,
      fontSize: newPaint.suffix.fontSize + 'px',
      fontWeight: newPaint.suffix.bold ? 'bold' : 'normal',
      lineHeight: newPaint.suffix.lineHeight + 'em'
    })
    if (!countup.error) {
      countup.start()
    } else {
      console.error(countup.error)
    }
    this.value = value
  }
}

export default Metric
