<template>
  <div class="label-tree-view"
       ref="main"
       :class="{target: target}"
       draggable="true" @dragstart="dragstart" @dragend="dragend"
       @dragover="dragover" @dragleave="dragleave" @drop="drop">
    <editable-headline :value="label.name"
                       @change="editLabel(label.identifier, $event)"
                       @remove="removeLabel(label.identifier)">
      <img v-if="collapse"
           src="@/assets/icons/triangle-down.svg"
           :style="{opacity: label.children.length > 0 ? 1 : 0.1}"
           @click="collapse = false">
      <img v-else
           src="@/assets/icons/triangle-up.svg"
           :style="{opacity: label.children.length > 0 ? 1 : 0.1}"
           @click="collapse = true">
    </editable-headline>

    <template v-if="!collapse">
      <label-tree-view v-for="child of label.children" :key="child.identifier"
                       :label="child"
                       :indent="indent"
                       :targetable="droppable"
                       :style="margin"/>
    </template>
  </div>
</template>

<script>
import EditableHeadline from "@/components/base/editable-headline";

export default {
  name: "LabelTreeView",
  components: {EditableHeadline},
  props: ['label', 'indent', 'targetable'],
  data: function () {
    return {
      untouched: true,
      target: false,
      collapse: false
    }
  },
  computed: {
    droppable: function () {
      return this.targetable && this.untouched;
    },
    margin: function () {
      return {
        marginLeft: this.indent
      };
    }
  },
  methods: {
    editLabel: function (id, value) {
      // TODO then / error
      this.$root.socket.post(`/projects/${this.$root.project.identifier}/labels/${id}/name`, {name: value});
    },
    removeLabel: function (id) {
      // TODO then / error
      this.$root.socket.post(`/projects/${this.$root.project.identifier}/labels/${id}/remove`, {remove: true});
    },
    dragstart: function (e) {
      this.untouched = false;
      e.dataTransfer.setData('text/identifier', this.label.identifier)
      e.stopPropagation();
    },
    dragend: function () {
      this.untouched = true;
    },
    dragover: function (e) {
      e.stopPropagation();

      if (this.droppable) {
        e.preventDefault();
        this.target = true;
      }
    },
    dragleave: function () {
      this.target = false;
    },
    drop: function (e) {
      e.preventDefault();
      e.stopPropagation();
      this.dragleave();

      const element = e.dataTransfer.getData('text/identifier');
      const parent = this.label.identifier;
      this.$root.socket.post(`/projects/${this.$root.project.identifier}/labels/${element}/parent`, {parent: parent});
    }
  }
}
</script>

<style scoped>
.editable-headline {
  margin-bottom: 0.5rem;
}

.target > .editable-headline {
  text-decoration: underline;
}
</style>
