<template>
  <HiveInputTag
    v-if="multiple"
    v-bind="$attrs"
    v-on="listeners"
    :suffix-icon="_suffixIcon"
    :placeholder="_placeholder"
    :tags="value"
    :value="inputValue"
    @blur="onBlur"
    @input="onInput"
    @tag-delete="$listeners['tag-delete']"
  />
  <HiveInput
    v-else
    v-bind="$attrs"
    v-on="listeners"
    :suffix-icon="_suffixIcon"
    :placeholder="_placeholder"
    :value="inputValue"
    @blur="onBlur"
    @input="onInput"
  />
</template>

<script>
import Input from './input';
import InputTag from './input-tag';

export default {
  components: {
    HiveInput: Input,
    HiveInputTag: InputTag
  },
  props: {
    multiple: Boolean,
    isFilteringMode: Boolean,
    placeholder: String,
    value: [Array, String],
    suffixIcon: String
  },
  data() {
    return {
      inputValue: this.$props.multiple ? '' : this.$props.value
    };
  },
  computed: {
    _suffixIcon() {
      return this.suffixIcon || this.multiple ? '' : 'carret_down';
    },
    _placeholder() {
      if (this.multiple) return this.value.length ? '' : this.placeholder;

      return (this.isFilteringMode && this.value) ? this.value : this.placeholder;
    },
    listeners() {
      const {
        'tag-delete': tagDelete,
        input,
        blur,

        ...others
      } = this.$listeners;

      return { ...others };
    }
  },
  watch: {
    value(value) {
      if (this.multiple) return;
      this.inputValue = value;
    }
  },
  methods: {
    onInput(value) {
      this.inputValue = value;
      this.$emit('input', value);
    },
    clearFilter() {
      this.inputValue = '';
    },
    focus() {
      if (this.isFilteringMode) this.inputValue = '';
    },
    onBlur(e) {
      if (this.isFilteringMode && !this.multiple && !this.inputValue) this.inputValue = this.value;
      this.$emit('blur', e);
    }
  }
};
</script>
