<template>
  <div class="itf-radio-box form-check card" :class="{ 'disabled': disabled, 'itf-radio__large': large, 'itf-radio__medium': medium, 'active': isChecked, 'right': right, 'left': !right }">
    <input class="form-check-input" :id="id" type="radio" :name="radioName" v-model="isChecked" :value="true" :disabled="disabled" />
    <label :for="id" slot="label" class="form-check-label card-body">

      <slot>
        <div>{{label}}</div>
        <small v-if="helpText" v-text="helpText" class="text-muted" />
      </slot>

    </label>
  </div>
</template>
<style lang="scss">
.itf-radio-box.card {
  padding: 0;
  margin-bottom: .5rem;
  position: relative;
  &:not(.disabled) {
    cursor: pointer;

    .form-check-label {
      cursor: pointer;
    }
  }

  .form-check-label {
    cursor: not-allowed;
  }

  &.left {
    padding: 0 0 0 2.5rem;

    .form-check-input {
      position: absolute;
      left: 3rem;
      top: 1rem;
    }
  }
  &.right {
    .form-check-input {
      position: absolute;
      right: 1.5rem;
      top: 1rem;
    }
  }

  &.active {
    background-color: rgba(var(--bs-primary-rgb),.1) !important;
  }
  &:hover:not(.disabled) {
    background-color: rgba(0,0,0,.05);
  }
}
</style>
<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(String) helpText;
  @Prop() value;
  @Prop({ type: String }) name;

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

  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>
