<template>
  <div class="itf-radio form-check" :class="{ 'itf-radio__large': large, 'itf-radio__medium': medium }">
    <input class="form-check-input" :id="id" type="radio" :name="radioName" v-model="isChecked" :value="true" :disabled="disabled" />
    <label :for="id" class="form-check-label">
      <slot name="label">
        {{label}}
        <slot name="icon"></slot>
      </slot>
    </label>
  </div>
</template>
<script>
import { Vue, Component, Prop, Model, Inject } from 'vue-property-decorator';

let globalRadioId = 0;

export default @Component({
  name: 'itfRadio',
  components: {
  }
})
class itfRadio extends Vue {
  @Inject({ default: null }) radioGroup;

  @Model('input') checked;
  @Prop(String) label;
  @Prop() value;
  @Prop({ type: String }) name;

  @Prop(Boolean) disabled;
  @Prop(Boolean) medium;
  @Prop(Boolean) large;

  id = '';

  created() {
    globalRadioId += 1;
    this.id = `radio${globalRadioId}`;
  }

  get radioName() {
    if (this.radioGroup) {
      return this.radioGroup.getGroupName();
    }
    if (!this.name) {
      throw new Error('Name for radio should be not empty');
    }
    return this.name;
  }

  set isChecked(val) {
    if (this.radioGroup) {
      this.radioGroup.onToggleOption(this.value, val);
    }
    this.$emit('input', this.value);
  }

  get isChecked() {
    if (this.radioGroup) {
      return this.radioGroup.isChecked(this.value);
    }
    if (this.itemKey) {
      if (!this.checked || !this.value) {
        return false;
      }
      return this.checked[this.itemKey] === this.value[this.itemKey];
    }
    return this.checked === this.value;
  }
}
</script>
