<template>
  <div class="mc-checkbox" :class="[type === 'block' ? '' : 'is-inline',{'is-disabled': disabled}]">
    <input 
      type="checkbox"
      :id="id"
      :name="name"
      :value="value"
      :required="required"
      @change="onChange"
      :checked="state"
      :disabled="disabled"
    />
    <label :for="id">
      <span class="mc-checkbox_inner">
        <i class="mc-checkbox_tick"></i>
      </span><slot></slot>
    </label>
  </div>
</template>

<script>
  export default {
    model: {
      prop: 'modelValue',
      event: 'input'
    },
    props: {
      id: {
        type: String,
        default: function () {
          return 'checkbox-id-' + this._uid;
        },
      },
      name: {
        type: String,
        default: null,
      },
      value: {
        type: String|Number,
        default: null,
      },
      modelValue: {
        type: String | Array,
        default: undefined,
      },
      type: {
        type: String,
        default: 'inline'
      },
      checked: {
        type: Boolean,
        default: false,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      required: {
        type: Boolean,
        default: false,
      },
      model: {}
    },
    computed: {
      state () {
        if (this.modelValue === undefined){
          return this.checked;
        }
        if (Array.isArray(this.modelValue)) {
          return this.modelValue.indexOf(this.value) > -1;
        }
        return !!this.modelValue;
      }
    },
    methods: {
      onChange(ev) {
        this.$emit('change', ev);
        this.toggle();
      },
      toggle() {
        let value;
        if (Array.isArray(this.modelValue)) {
          value = this.modelValue.slice(0);
          if (this.state) {
            value.splice(value.indexOf(this.value), 1);
          } else {
            value.push(this.value);
          }
        } else {
          value = !this.state;
        }
        this.$emit('input', value);
      }
    },
    watch: {
      checked(newValue) {
        if (newValue !== this.state) {
          this.toggle();
        }
      }
    },
    mounted() {
      if (this.checked && !this.state) {
        this.toggle();
      }
    },
  };
</script>