export default {
  name: 'BaseCheckbox',
  inheritAttrs: false,
  model: {
    prop: 'valueChecked',
    event: 'change',
  },
  props: {
    label: {
      type: String,
    },
    description: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String | Number | Boolean,
      default: true,
    },
    valueChecked: {
      type: String | Number | Boolean | Array,
    },
    uncheckedValue: {
      type: String | Number | Boolean,
      default: false,
    },
    error: {
      type: String,
      default: '',
    },
    inline: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: 'medium',
      validator(value) {
        return ['small', 'medium', 'large'].indexOf(value) !== -1;
      },
    },
  },
  computed: {
    classSize() {
      return {
        'checkbox-small': this.size === 'small' && this.label,
        'checkbox-medium': this.size === 'medium' && this.label,
        'checkbox-large': this.size === 'large' && this.label,
      };
    },
    isChecked() {
      if (typeof this.valueChecked === 'object') {
        const valueCheckedIndex = this.valueChecked.findIndex(value => value == this.value);
        return valueCheckedIndex !== -1;
      }

      return this.valueChecked == this.value;
    },
    inputListeners() {
      return Object.assign({}, this.$listeners, {
        change: event => {
          const inputIsChecked = event.target.checked;
          const valueCheckedIsObject = typeof this.valueChecked === 'object';

          let issuedValue = this.uncheckedValue;

          if (inputIsChecked) {
            issuedValue = valueCheckedIsObject ? [...this.valueChecked, this.value] : this.value;
          } else {
            if (valueCheckedIsObject) {
              const valueCheckedIndex = this.valueChecked.findIndex(value => value == this.value);
              this.valueChecked.splice(valueCheckedIndex, 1);
              issuedValue = this.valueChecked;
            }
          }

          this.$emit('change', issuedValue);
        },
      });
    },
  },
};
