<template>
  <label class="switch" :class="switchClasses">
    <input type="checkbox" :disabled="disabled" v-model="currentValue" style="display: none;"><span class="switchery" :class="classes" ref="switchery"><small :class="{open:currentValue,close:!currentValue}"></small></span>
    <slot></slot>
  </label>
</template>
<script>
const sizeArray = ['xlg', 'lg', 'sm', 'xs']
export default {
  name: 'ISwitch',
  props: {
    disabled: Boolean,
    value: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'lg',
      validator: function(value) {
        return sizeArray.includes(value)
      }
    }
  },
  data() {
    return {
      currentValue: this.value,
      ifChangeByValue:false
    }
  },
  mounted() {
    this.$refs.switchery.classList.add(`switchery-${this.size}`)
  },
  watch: {
    currentValue(val) {
      if(!this.ifChangeByValue){
        this.$emit('on-change', val)
      } else {
        this.ifChangeByValue = false
      }
    },
    value(val){
      this.currentValue = val
      this.ifChangeByValue = true
    }
  },
  computed: {
    classes() {
      let li = [`switchery-${this.size}`]
      if (this.currentValue) {
        li.push('open')
      } else {
        li.push('close')
      }

      if (this.disabled) {
        li.push('disabled')
      }

      return li.join(' ')
    },
    switchClasses() {
      let li = [`switch-${this.size}`]
      if (this.disabled) {
        li.push('disabled')
      }
      return li.join(' ')
    }
  }

}
</script>
