<script>
export default {
  props: {
    id: {default: ''},
    is_disabled: {default: false},
    format: {default: ''},
    is_submitted: {default: false},
    size: {default: 'md'},
    value: {default: ''},
    placeholder: {default: ''},
    is_error: {default: false},
    max_length: {default: 524288},
    additional_class: {default: ''}
  },
  data() {
    return {
      input_class: "form-control",
    }
  },

  watch: {
    is_error: function () {
      this.generateInputClass()
    },

    is_submitted: function () {
      this.generateInputClass()
    },
  },

  methods: {
    updateToParent(value) {
      if (typeof this.format === "Array") {
        alert("array")
      } else {
        value = this.reformatText(this.format, value)
      }
      this.$emit('input', (value) ? value : '')
      document.getElementById(this.id).value = value
    },

    submitToParent() {
      this.$emit("submit")
    },

    reformatText(type, text) {
      switch (type) {
        case 'number' :
          return this.$utility.removeLetter(text)
        case 'currency' :
          text = this.$utility.removeLetter(text)
          text = this.$utility.convertToNumber(text)
          return this.$utility.convertToRupiah(text)
        case 'letter' :
          return this.$utility.removeNumber(text)
        case 'no-symbol' :
          return this.$utility.removeSymbols(text)
        default :
          return text
      }
    },

    convertSizeToClass(size) {
      switch (size) {
        case  'md' :
          return 'form-control'
          break;
        case  'sm' :
          return 'form-control-sm'
          break;
        case  'lg' :
          return 'form-control-lg'
          break;
        default:
          return "form-control"
      }
    },

    generateInputClass() {
      if (this.is_submitted && this.is_error) {
        this.input_class = `${this.convertSizeToClass(this.size)} is-invalid ${this.additional_class}`
      } else {
        this.input_class = `${this.convertSizeToClass(this.size)} ${this.additional_class}`
      }
    },
  }
}
</script>
<template>
  <input :value="(value) ? value : ''" v-on:keyup="updateToParent($event.target.value)" @keyup.enter="submitToParent"
         :class="input_class" :id="id" :disabled="is_disabled" :maxlength="max_length" :placeholder="placeholder"/>
</template>
<style>
input::placeholder {
  color: #cecece !important;
}
</style>