import { makeError } from '../common.js'
import { locale as L } from '../lang/zh_TW'
import $ from 'jquery'

const _properties = new WeakMap()

function Unit (val) {
  let _val = 0
  if (!(this instanceof Unit)) return new Unit(val)
  if (val !== undefined) {
    if (typeof (val) === 'string') {
      var exp = new RegExp('^([+-]?\\d+(\\.\\d+)*)(' + (Object.keys(Unit.supportUnit).join('|')) + ')?$', 'i')
      var m = val.match(exp)
      if (m != null) {
        _val = parseFloat(m[1]) * Unit.supportUnit[(m[3] || 'px')]
      } else {
        makeError('ERR_BAD_PARAMETERS', L`_STR_ERR_BAD_PARAMETERS`)
      }
    } else if (typeof (val) === 'number') {
      _val = val
    } else if (val instanceof Unit) {
      return val
    } else {
      makeError('ERR_BAD_PARAMETERS', L`_STR_ERR_BAD_PARAMETERS`)
    }
  }
  _properties.set(this, {
    val: _val
  })
}

var prototype = Unit.prototype

Unit.supportUnit = (function () {
  var m = $('<div>').css('overflow', 'hidden').height('1px')
  var n = $('<div>')
  $('body').append(m.append(n))
  const result = {
    px: 1,
    mm: n.height('2000mm').height() / 2000,
    cm: n.height('2000cm').height() / 2000,
    in: n.height('1000in').height() / 1000
  }
  m.remove()
  return result
})()

Unit.defaultUnit = 'px'

for (const i in Unit.supportUnit) {
  (function (u, U) {
    Object.defineProperty(prototype, u, { get: function () { return this.to(u) } })
    Object.defineProperty(prototype, U, { get: function () { return this.to(u, true) } })
  })(i, i.toUpperCase())
}

prototype.valueOf = function valueOf () {
  return this.to(Unit.defaultUnit)
}

prototype.to = function to (unit, useUnitExt) {
  const _ = _properties.get(this) || {}
  var result
  if (Unit.supportUnit[unit] !== undefined) {
    result = _.val / Unit.supportUnit[unit]
  }
  return (useUnitExt ? result + unit : result)
}

export default Unit
