export default {
  name: 'BaseRadio',
  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,
    },
    inline: {
      type: Boolean,
      default: false,
    },
    error: {
      type: String,
      default: '',
    },
    size: {
      type: String,
      default: 'medium',
      validator(value) {
        return ['small', 'medium', 'large'].indexOf(value) !== -1;
      },
    },
  },
  computed: {
    classSize() {
      return {
        'radio-small': this.size === 'small' && this.label,
        'radio-medium': this.size === 'medium' && this.label,
        'radio-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);
        },
      });
    },
  },
};
