<template>
  <div class="kole-switchgroup">
    <div class="kole-switchgroup-head" v-if="title || selectAll">
      <span class="kole-switchgroup-title">{{ title }}</span>
      <div v-if="selectAll" class="kole-switch" :class="{ 'is-on': allOn }" @click="toggleAll"></div>
    </div>
    <div class="kole-switch-row" v-for="(o, i) in options" :key="i">
      <div class="kole-switch-text">
        <span class="kole-switch-label">{{ o.label }}</span>
        <span class="kole-switch-desc" v-if="o.desc">{{ o.desc }}</span>
      </div>
      <div class="kole-switch" :class="{ 'is-on': value.indexOf(o.value) >= 0 }" @click="toggle(o.value)"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KoleSwitchGroup',
  props: {
    options: { type: Array, default: function () { return []; } },
    value: { type: Array, default: function () { return []; } },
    title: { type: String, default: '' },
    selectAll: { type: Boolean, default: false }
  },
  computed: {
    allOn: function () {
      return this.options.length > 0 && this.options.every(function (o) { return this.value.indexOf(o.value) >= 0; }, this);
    }
  },
  methods: {
    toggle: function (v) {
      var arr = this.value.slice();
      var idx = arr.indexOf(v);
      if (idx >= 0) arr.splice(idx, 1); else arr.push(v);
      this.$emit('input', arr);
    },
    toggleAll: function () {
      var next = this.allOn ? [] : this.options.map(function (o) { return o.value; });
      this.$emit('input', next);
    }
  }
};
</script>

<style src="./SwitchGroup.css"></style>
