<template>

  <div class="itf-textarea" :class="{ 'with-addon addon-start': prependIcon, 'itf-textarea__autogrow': autogrow, 'p-0': !hasContent }">
    <div class="p-2 itf-textarea__content" v-if="hasContent">
      <slot></slot>
    </div>

    <div class="position-relative" :class="{'input-group': prependIcon}">
      <div class="addon" v-if="prependIcon">
        <slot name="addon">
          <itf-icon :name="prependIcon"/>
        </slot>
      </div>

      <div v-if="autogrow" class="itf-textarea__autogrow-text form-control" :class="{'pt-5': hasContent}">{{value}}&nbsp;</div>
      <textarea
        ref="input"
        :rows="rows"
        :readonly="readonly"
        :disabled="disabled"
        :placeholder="placeholder"
        :class="{ 'is-invalid': isInvalid(), 'is-valid': isSuccess(), 'pt-5': hasContent }"
        class="itf-textarea__input form-control"
        :value="value"
        @input="onInput($event.target.value)"
        @keydown="$emit('keydown', $event)"
        @keyup="$emit('keyup', $event)"
        @keypress="$emit('keypress', $event)"
        @blur="$emit('blur', $event)"
        @focus="$emit('focus', $event)"
      />
    </div>
  </div>

</template>
<script>
import { Vue, Component, Model, Inject, Prop } from 'vue-property-decorator';
import itfIcon from '../icon/Icon';
import itfButton from '../button/Button';
import { debounce } from '../../helpers/debounce';

export default @Component({
  name: 'itfTextarea',
  components: {
    itfIcon,
    itfButton
  }
})
class itfTextarea extends Vue {
  @Inject({ default: null }) itemLabel;
  @Model('input') value;
  @Prop(String) prependIcon;
  @Prop(String) placeholder;
  @Prop(Boolean) autogrow;
  @Prop(Boolean) disabled;
  @Prop(Boolean) readonly;
  @Prop({ type: [Number, String], default: 0 }) delayInput;
  @Prop({ type: [Number, String] }) rows;

  onInput = null;

  get hasContent() {
    return !!this.$slots.default;
  }

  created() {
    this.onInput = debounce((val) => this.$emit('input', val), Number(this.delayInput));
  }

  isInvalid() {
    return this.itemLabel && this.itemLabel.isHasError();
  }

  isSuccess() {
    return this.itemLabel && this.itemLabel.isHasSuccess();
  }

  insertTextToCurrentPosition(text) {
    const position = this.$refs.input.selectionStart;
    const value = this.value || '';
    const startText = value.slice(0, position);
    const endText = value.slice(position);
    this.$emit('input', `${startText}${text}${endText}`);
  }

  focus() {
    this.$refs.input.focus();
  }

  blur() {
    this.$refs.input.blur();
  }
}
</script>
