<!--
  Program: RegexInput
  Author: SDL
  Brief: Input using regex
-->
<template>
  <input v-bind="$attrs" @input="updateValue($event.target.value)" @change="emitChange" v-model="val" ref="input" />
</template>

<script>
import _ from 'lodash';

export default {
  name: 'sdl-regex-input',
  props: {
    value: {
      required: false,
      type: [Number, String],
    },
    modelValue: {
      required: false,
      type: [Number, String],
    },
    regExp: {
      type: RegExp,
      default: null,
    },
  },
  data() {
    return {
      val: '',
      oldVal: '',
    };
  },
  methods: {
    isValid(val) {
      return _.isEmpty(val) || val.toString().match(this.regExp);
    },
    // update the value of input
    updateValue(val) {
      const newValue = this.isValid(val) ? val : this.oldVal;
      this.val = newValue;
      this.oldVal = newValue;
      this.emitInput(newValue);
    },
    // emit input event
    emitInput(val) {
      this.$emit('input', val);
      this.$emit('update:modelValue', val);
    },
    // emit change event
    emitChange() {
      this.$emit('change', this.val);
      this.$emit('update:modelValue', this.val);
    },
  },
  watch: {
    // watch value prop
    value(val) {
      this.updateValue(val);
    },
    modelValue(val) {
      this.updateValue(val);
    },
  },
  mounted() {
    this.updateValue(this.modelValue);
  },
};
</script>
