<template>
  <div class="mm-checkbox-group">
    <component
      :is="componentType"
      v-for="item of options"
      :key="getVal(item, keyKey)"
      v-model="localValue"
      :on-change="onChange"
      :disabled="getVal(item, disabledKey) || realDisabled"
      :label="getVal(item, labelKey)"
      :value="getVal(item, valueKey)"
      @change="handleChange">
      <slot v-bind="item"></slot>
    </component>
  </div>
</template>
<script>
import input from "../../mixins/input"
import Checkbox from "../checkbox/checkbox"
import CheckboxButton from "./checkbox-button"
import config from "../../managers/config"
import get from "lodash/get"

config.defaults({
  "CheckboxGroup.type": "checkbox",
})

export default {
  name: "mm-checkbox-group",
  components: {
    "ui-checkbox": Checkbox,
    "ui-checkbox-button": CheckboxButton,
  },
  mixins: [input],
  model: {
    prop: "value",
    event: "input",
  },
  props: {
    value: {
      type: Array,
    },
    type: {
      type: String,
      default: () => config.get("CheckboxGroup.type"),
      validator(val) {
        return ["checkbox", "button"].includes(val)
      },
    },
    options: {
      type: Array,
      default: () => [],
    },
    onChange: Function,
    keymap: {
      type: Object,
      default() {
        return {}
      },
    },

  },
  data() {
    return {
      localValue: this.value,
    }
  },
  computed: {
    componentType() {
      const mapping = {
        checkbox: "ui-checkbox",
        button: "ui-checkbox-button",
      }

      return mapping[this.type]
    },
    keyKey() {
      return this.keymap.key || "value"
    },
    labelKey() {
      return this.keymap.label || "label"
    },
    valueKey() {
      return this.keymap.value || "value"
    },
    disabledKey() {
      return this.keymap.disabled || "disabled"
    },
  },
  watch: {
    value(val) {
      this.localValue = val
    },
    localValue(val) {
      this.$emit("input", val)
    },
  },
  methods: {
    handleChange(value, event) {
      this.$emit("change", event, this.localValue)
    },
    getVal: get,
  },
}
</script>
