<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" v-if="tasks.childList.length">
          <svg-icon type="mdi" :width="18" :height="18" :path="icon" :color="'#5089ef'"></svg-icon>
        </div>
          <div class="gd-10">
            <p class="node-name ml5" :title="tasks.nm">{{ tasks.nm }}</p>
          </div>
        </div>
      </div>
      <svg-icon
        class="handle gd-1"
        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>

<style scoped>
.p-tree {
  padding: 0.5rem 0;
}

.node-name {
  font-size: 1.6rem;
}

.selected {
  border: 1px solid var(--blue);
  border-radius: 0.3rem;
}

.ghost {
  height: 15px;
  color: transparent;
  border: 1px dashed var(--blue);
}
.ghost * {
  display: none;
}
</style>