<template>
  <div :class="['float-label', { filled: filled }, { error: hasErrors }]">
    <input
      :id="inputId"
      :name="inputId"
      type="text"
      class="float-label__input"
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
      @focus="addFloatLabelClass"
      @blur="removeFloatLabelClass">
    <label :for="inputId" class="float-label__text">{{inputLabel}}</label>
    <span v-show="hasErrors" class="float-label__warning">This field is required</span>
  </div>
</template>

<script>
export default {
  data () {
    return {
      filled: false,
      errors: []
    }
  },
  props: {
    inputId: {
      type: String,
      required: true
    },
    inputLabel: {
      type: String,
      required: true
    },
    value: {
      type: String,
      default: null
    },
    required: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    hasErrors () {
      return this.errors.length > 0
    }
  },
  methods: {
    addFloatLabelClass () {
      this.filled = true
    },
    removeFloatLabelClass () {
      if (!this.value) this.filled = false
    },
    validate () {
      this.errors = []
      if (this.required && this.isBlank(this.value)) {
        this.errors.push('this field is required')
      }
      return {
        hasErrors: this.hasErrors,
        errors: this.errors
      }
    },
    isBlank (value) {
      const PRIMITIVE_BLANK_VALUES = ['', null, undefined]

      const isEmptyObject =
        typeof value === 'object' &&
        value !== null &&
        Object.keys(value).length === 0

      const isEmptyArray = Array.isArray(value) && value.length === 0

      return PRIMITIVE_BLANK_VALUES.includes(value) || isEmptyObject || isEmptyArray
    }
  },
  mounted () {
    if (this.value) this.filled = true
  }
}
</script>
