<template>
  <div class="bx-checkbox">
    <div 
      :class="['bx-checkbox-icon',`bx-checkbox-${shape}`,{ 'bx-checkbox-checked': checked }]" 
      @click="toggle"
      >
      <slot 
        name="icon" 
        :checked="checked"
        >
        <bxs-icon 
          name="check" 
          size="12px" 
          :style="iconStyle"
          />
      </slot>
    </div>
    <span
      v-if="$slots.default"
      class="bx-checkbox-label"
      @click="toggle"
      >
      <slot />
    </span>
  </div>
</template>
<script>
import { create } from '../utils'
import Icon from '../icon/index'

const onlyValues = values => str => values.indexOf(str) !== -1
export default create({
  name: 'checkbox',

  components: {
    [Icon.name]: Icon,
  },
  props: {
    name: null,
    shape: {
      type: String,
      default: 'round',
      validator: onlyValues(['round', 'square']),
    },
    value: {
      type: Boolean,
      default: false,
    },
    checkedColor: String,
  },
  data() {
    return {
      parent: null,
    }
  },
  computed: {
    checked: {
      get() {
        return this.parent
          ? this.parent.value.indexOf(this.name) !== -1
          : this.value
      },

      set(val) {
        if (this.parent) {
          this.setParentValue(val)
        } else {
          this.$emit('input', val)
        }
      },
    },

    iconStyle() {
      const { checkedColor, checked } = this
      if (checkedColor && checked) {
        return {
          borderColor: checkedColor,
          backgroundColor: checkedColor,
        }
      }
      return {}
    },
  },

  watch: {
    value(val) {
      this.$emit('change', val)
    },
  },

  created() {
    this.findParent('bxs-checkbox-group')
  },

  methods: {
    toggle() {
      this.checked = !this.checked
    },

    setParentValue(val) {
      const { parent } = this
      const value = parent.value.slice()

      if (val) {
        if (parent.max && value.length >= parent.max) {
          return
        }

        if (value.indexOf(this.name) === -1) {
          value.push(this.name)
          parent.$emit('input', value)
        }
      } else {
        const index = value.indexOf(this.name)

        if (index !== -1) {
          value.splice(index, 1)
          parent.$emit('input', value)
        }
      }
    },

    findParent(name) {
      let parent = this.$parent
      while (parent) {
        if (parent.$options.name === name) {
          this.parent = parent
          break
        }
        parent = parent.$parent
      }
    },
  },
})
</script>
<style>
@import './index.css';
</style>
