<template>
  <Input ref="xInput" @input.native='inputHandler' @on-blur="onblur" On-focus="onfucus"/>
</template>
<script>
import create from '../utils/create'
import { Input } from 'view-design'
import Inputmask from 'inputmask'

export default create({
  name: 'pattern-input',
  components: {
    Input
  },
  props: {
    value: {
      required: false,
      validator (val) {
        return typeof val === 'string' || val === '' || val === null
      }
    },
    pattern: {
      type: RegExp,
      default: null
    },
    mask: {
      required: false,
      type: [Object, String],
      default: () => {
        return ''
      }
    },
    splitChar: {
      type: String,
      default: () => {
        return ' '
      }
    }
  },
  data () {
    return {
      currentValue: this.value,
      element: null,
      splitRegex: new RegExp('[' + this.splitChar + ']', 'g')
    }
  },
  methods: {
    inputHandler () {
      this.currentValue = this.element.inputmask.unmaskedvalue()
    },
    isComplete () {
      let val = '' || this.element.value
      let curVal = '' || this.element.currentValue
      if (val !== '' && curVal !== '') {
        return this.element.inputmask.isComplete()
      }
      return true
    },
    onblur (event) {
      this.$emit('blur', event)
    },
    onfucus (event) {
      this.$emit('focus', event)
    }
  },
  mounted () {
    this.element = this.$refs.xInput.$el.querySelector('input')
    if (this.mask) {
      Inputmask(this.mask).mask(this.element)
      this.element.inputmask.setValue(this.value)
    } else if (this.pattern) {
      Inputmask({ regex: this.pattern.source,
        isComplete: (buffer, opts) => {
          return this.pattern.test(buffer.join(''))
        }
      }).mask(this.element)
      this.element.inputmask.setValue(this.value)
    }
  },
  watch: {
    currentValue (val) {
      if (!val) val = ''
      val = val.replace(this.splitRegex, '')
      this.$emit('input', val)
    },
    value (val) {
      if (!val) val = ''
      val = val.replace(this.splitRegex, '')
      this.element.inputmask.setValue(val)
      this.$emit('input', val)
    }
  }
})
</script>
