<template>
  <li>
    <div :class="{ 'node-wrap': true, selected: displaySelectedNode === tasks.id, }" @click="toggleNode(tasks.id)" >
      <div class="node">
        <div class="arrow-img" v-if="tasks.childList.length">
          <svg-icon type="mdi" :width="18" :height="18" :path="iconPath()" style="vertical-align: sub;"></svg-icon>
        </div>
        <div class="node-name-wrap">
            <img :src="require(`/client/resources/img/admin/${icon}.svg`)" alt="" v-if="tasks.childList.length">
            <span v-else class="bullet"></span>
          <div :title="tasks.nm">
            <p class="node-name">{{ tasks.nm }}</p>
          </div>
        </div>
      </div>
      <svg-icon
        class="handle"
        type="mdi"
        :width="18"
        :height="18"
        :path="iconDrag()"
      ></svg-icon>
    </div>
    <draggable
      v-if="isOpen || tasks.childList.length == 0"
      tag="ul"
      class="child-node pl20"
      :list="tasks.childList"
      :group="{ name: 'menu' }"
      item-key="id"
      handle=".handle"
      ghost-class="ghost"
    >
      <template #item="{ element }">
        <Hierachy
          :tasks="element"
          :icon="icon"
          :selectedNode="selectedNode"
          @changeSelected="findByChildNode"
        />
      </template>
    </draggable>
  </li>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "Hierachy",
  props: {
    tasks: {
      type: Array,
      required: true,
    },
    icon: {
      required: true,
    },
    selectedNode: {
      type: String,
    },
  },
  data() {
    return {
      isOpen: false,
    };
  },
  methods: {
    toggleNode(node) {
      this.isOpen = !this.isOpen;
      this.$emit("changeSelected", node);
    },
    iconPath() {
      return this.isOpen ? this.$iconPath("mdiChevronDown") : this.$iconPath("mdiChevronRight");
    },
    iconDrag() {
      return this.$iconPath("mdiDrag");
    },
    findByChildNode(node) {
      this.$emit("changeSelected", node);
    },
  },
  watch: {},
  computed: {
    displaySelectedNode() {
      return this.selectedNode;
    },
  },
  components: {
    draggable,
  },
};
</script>
