<template>
  <div
    class="mm-radio-group">
    <component
      :is="componentType"
      v-for="item of options"
      :key="item.value"
      v-model="localValue"
      :disabled="item.disabled || realDisabled"
      :name="localName"
      v-bind="item">
      <slot v-bind="item"></slot>
    </component>
  </div>
</template>

<script>
import uniqueId from "lodash/uniqueId"
import input from "../../mixins/input"
import Radio from "../radio/radio"
import RadioButton from "./radio-button"
import config from "../../managers/config"

config.defaults({
  "RadioGroup.type": "radio",
})

export default {
  name: "mm-radio-group",
  components: {
    "mm-radio": Radio,
    "mm-radio-button": RadioButton,
  },
  mixins: [input],
  model: {
    prop: "value",
    event: "input",
  },
  provide() {
    return {
      "mm-radio-group": this,
    }
  },
  props: {
    options: {
      type: Array,
      default: () => [],
    },
    value: null,
    type: {
      type: String,
      default: () => config.get("RadioGroup.type"),
      validator(val) {
        return ["radio", "button"].includes(val)
      },
    },
  },
  data() {
    return {
      localValue: this.value,
    }
  },
  computed: {
    localName() {
      return this.realName || uniqueId("mm-radio-group-")
    },
    componentType() {
      const mapping = {
        radio: "mm-radio",
        button: "mm-radio-button",
      }

      return mapping[this.type]
    },
  },
  watch: {
    value(val) {
      this.localValue = val
    },
    localValue(value) {
      this.$emit("input", value)
    },
  },
  methods: {
    handleChange(event, value) {
      this.$emit("change", event, value)
    },
  },
}
</script>
