import { IMaskDirective } from 'vue-imask';

import 'vue2-datepicker/locale/pt-br';

import maskOptions from '@assets/js/masks';

export default {
  name: 'BaseInput',
  components: {
    DatePicker: () => import(/* webpackChunkName: "DatePicker" */ 'vue2-datepicker'),
  },
  directives: {
    imask: IMaskDirective,
  },
  inheritAttrs: false,
  props: {
    name: {
      type: String,
    },
    label: {
      type: String,
    },
    description: {
      type: String,
    },
    size: {
      type: String,
      default: 'medium',
      validator(value) {
        return ['small', 'medium', 'large'].indexOf(value) !== -1;
      },
    },
    type: {
      type: String,
      default: 'text',
    },
    value: {
      type: String | Number,
    },
    error: {
      type: String,
    },
    valid: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    mask: {
      type: String,
    },
    ummask: {
      type: Boolean,
      default: false,
    },
    required: {
      type: Boolean,
      default: false,
    },
    select: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      maskOptions: maskOptions,
    };
  },
  computed: {
    classObject() {
      return {
        'field-disabled': this.disabled,
        'field-required': this.required,
        'field-error': this.error,
        'field-valid': this.valid,
      };
    },
    isDatePicker() {
      const isDatePickerWhenTypeIs = ['date', 'month', 'year', 'datetime', 'time', 'week'];

      const isUseToDatePicker = isDatePickerWhenTypeIs.findIndex(type => type === this.type);

      return isUseToDatePicker != -1;
    },
    inputListeners() {
      return Object.assign({}, this.$listeners, {
        input: event => {
          if (!this.mask) {
            this.$emit('input', event.target.value);
          }
        },
        accept: event => {
          const value = this.ummask ? event.target.maskRef.unmaskedValue : event.target.value;
          this.$emit('input', value);
        },
      });
    },
  },
  mounted() {
    if (this.mask && !this.isDatePicker) {
      this.$refs.input.dispatchEvent(new Event('accept'));
    }

    if (this.select) {
      const inputRef = this.$refs.input;
      inputRef.select();
      inputRef.focus();
    }
  },
};
