<template>

  <div>
    <slot />
  </div>

</template>
<script>
  import { Vue, Component, Prop, Model } from 'vue-property-decorator';

  export default @Component({
    name: 'itfCheckboxGroup',
    provide() {
      return { checkboxGroup: this }; // do not use Provide from vue-property-decorator
    }
  })
  class itfCheckboxGroup extends Vue {
    @Model('input', { type: Array, default: () => [] }) value;

    @Prop(Boolean) disabled;

    @Prop(String) itemKey;

    @Prop(Number) max;

    onToggleOption(value, isChecked) {
      const index = this.getCheckedIndex(value);
      const arr = this.value ? [ ...this.value ] : [];
      if (index !== -1 && isChecked === false) {
        arr.splice(index, 1);
      } else if (isChecked === true) {
        arr.push(value);
      }
      this.$emit('input', arr);
    }

    getCheckedIndex(value) {
      if (this.itemKey) {
        return this.value && this.value.findIndex(item => item[this.itemKey] === value[this.itemKey]);
      }
      return this.value.indexOf(value);
    }

    isChecked(value) {
      return this.getCheckedIndex(value) !== -1;
    }

    isDisabled(value) {
      return this.getCheckedIndex(value) === -1 && (this.max !== 'undefined' && this.value.length >= this.max);
    }
  }
</script>
