<template>
  <div class="dv-indicator-select" :class="classes">
    <div class="dv-indicator-select-title" v-if="title">{{title}}</div>
    <ul class="dv-indicator-select-list">
      <li class="dv-indicator-select-item"
          v-for="item in items"
          :key="item.name"
          @click="handleClick(item)"
          :class="{ active: isActive(item) }">
        <span>{{item[dimensions[0].name]}}</span>
      </li>
    </ul>
  </div>
</template>

<script>

  export default {
    name: 'DvIndicatorSelect',
    props: {
      title: null,
      dimensions: {
        type: Array,
        default () {
          return [];
        }
      },
      indexes: {
        type: Array,
        default () {
          return [];
        }
      },
      direction: {
        type: String,
        default: 'column'
      },
      items: {
        type: Array,
        default () {
          return [];
        }
      },
      theme: {
        type: String,
        default: 'light'
      },
      value: null,
      multi: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        active: this.value
      };
    },
    watch: {
      value (value) {
        this.active = value;
      }
    },
    computed: {
      classes () {
        return [this.theme, this.direction, { multi: this.multi }];
      }
    },
    methods: {
      isActive (item) {
        const value = item[this.indexes[0].name];
        if (this.multi) {
          return this.active ? this.active.includes(value) : false;
        }
        else {
          return value === this.active;
        }
      },
      handleClick (item) {
        const value = item[this.indexes[0].name];

        if (this.multi) {
          const index = this.active.findIndex(_ => _ === value);
          if (index !== -1) {
            this.active.splice(index, 1);
          }
          else {
            this.active.push(value);
          }
        }
        else {
          if (this.active !== value) {
            this.active = value;
            this.$emit('input', this.active, item);
          }
        }
      },
      onDataReady () {
        this.handleClick(this.items[0]);
      }
    }
  };
</script>
