<template>
  <label>
    <span>
      <input
        v-if="group"
        v-model="model"
        type="checkbox"
        :disabled="disabled"
        :value="label"
        @change="change"
      >
      <input
        v-else
        type="checkbox"
        :disabled="disabled"
        :checked="currentValue"
        @change="change"
      >
    </span>
    <slot></slot>
  </label>
</template>

<script>
import { findComponentUpward } from '../../../src/mixins/findComponents'
import emitter from '../../../src/mixins/emitter'
export default {
  name: 'ICheckbox',
  mixins: [emitter],
  props: {
    label: {
      label: [String, Number, Boolean]
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type:  [String, Number, Boolean],
      default: false,
    },
    trueValue: {
      type:  [String, Number, Boolean],
      default: true,
    },
    falseValue:{
      type:  [String, Number, Boolean],
      default: false
    }
  },
  data () {
    return {
      currentValue: this.value,
      group: false,
      parent: null,
      model: []
    }
  },
  watch: {
    value: {
      handler (nv) {
        if (nv === this.value || nv === this.falseValue) {
          this.updateModel()
        } else {
          throw 'Value should be trueValue or falseValue'
        }
      },
      immediate: true

    }
  },
  mounted () {
    this.parent = findComponentUpward(this, 'ICheckboxGroup')
    if (this.parent) {
      this.group = true
    }

    if (this.group) {
      this.parent.updateModel(true)
    } else {
      this.updateModel()
    }
  },
  methods: {
    updateModel () {
      this.currentValue = this.value === this.trueValue
    },
    change (event) {
      if (this.disabled) {
        return false
      }
      const checked = event.target.checked
      this.currentValue = checked

      const value = checked ? this.trueValue : this.falseValue

      if (this.group) {
        this.parent.change(this.model)
      } else {
        this.$emit('on-change', value)
        this.dispatch('iFormItem', 'on-form-change', value)
      }
    },
  },
}
</script>

<style lang="scss" scoped>

</style>
