<template lang="pug">
  div.cpt-tree-node.relative()
    div.handler
      span.icon.icon-spander(:class="[icon]" @click="toggleHandler(nodeData)")
      Checkbox(:value="nodeData.selected" :indeterminate="getIndeterminate()" @click.native.prevent="selectHandler(nodeData)")
      span.text {{nodeData.title}}
    cpt-tree-node(v-if="hasChildren" v-show="nodeData.open" :key="item"  v-for="item in nodeData.children" @on-change="selectHandler" @on-toggle="toggleHandler(item)"  :nodeData="item")
</template>

<script>
import _ from 'lodash';
export default {
  name: 'cpt-tree-node',
  props: {
    nodeData: Object,
    level: {
      type: Number,
      default() {
        return 0;
      }
    }
  },
  computed: {
    hasChildren() {
      return this.nodeData.children && this.nodeData.children.length;
    },
    icon() {
      if (this.hasChildren) {
        return this.nodeData.open ? 'icon-down-dir' : 'icon-right-dir';
      }
    }
  },
  methods: {
    getIndeterminate() {
      let selectedChildren = _.filter(this.nodeData.children, child => {
        return child.selected;
      });
      return selectedChildren.length > 0 && selectedChildren.length < this.nodeData.children.length;
    },
    selectHandler(nodeData) {
      this.$emit('on-change', nodeData);
    },
    toggleHandler(nodeData) {
      this.$emit('on-toggle', nodeData);
    }
  }
};
</script>

