<template>
  <li>
    <div
      :class="{
        'flex align-center justify-between cursor p-tree no-gutters': true,
        selected: displaySelectedNode === tasks.id,
      }"
      @click="toggleNode(tasks.id)"
    >
      <div class="gd-11 flex align-center no-gutters">
        <div class="gd-1" v-if="tasks.childList.length">
          <svg-icon
            type="mdi"
            :width="18"
            :height="18"
            :path="iconPath()"
          ></svg-icon>
        </div>
        <div class="gd-11 flex align-center">
          <div class="gd-1">
            <svg-icon
              type="mdi"
              v-if="tasks.childList.length"
              :width="18"
              :height="18"
              :path="icon"
              :color="'#5089ef'"
            ></svg-icon>
          </div>
          <div class="gd-10 cursor" :title="tasks.nm">
            <p class="node-name">{{ tasks.nm }}</p>
          </div>
        </div>
      </div>
      <svg-icon
        class="gd-1 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";
import { mdiChevronRight, mdiChevronDown, mdiDrag } from "@mdi/js";

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 ? mdiChevronDown : mdiChevronRight;
    },
    iconDrag() {
      return mdiDrag;
    },
    findByChildNode(node) {
      this.$emit("changeSelected", node);
    },
  },
  watch: {},
  computed: {
    displaySelectedNode() {
      return this.selectedNode;
    },
  },
  components: {
    draggable,
  },
};
</script>
