<template>
    <tree
            draggable
            cross-tree
            :data="sekcie"
            @change="onChange"
    >
        <div
                slot-scope="{data, store}"
        >
            <template
                    v-if="!data.isDragPlaceHolder"
            >
                <b
                        style="font-weight: bold; font-size: 1.3em;"
                        v-if="data.children && data.children.length"
                        @click="store.toggleOpen(data)"
                >
                    {{data.open ? '-' : '+'}}
                </b>
                <span class="ml-1">{{data.nazov}}</span>
                <kontextove-menu
                        :sekcia="data"
                ></kontextove-menu>
            </template>
        </div>
    </tree>
</template>

<script>
  import {DraggableTree} from 'vue-draggable-nested-tree'
  import KontextoveMenu from './components/KontextoveMenu'

  export default {
    name: 'ZoznamComponent',
    components: {
      Tree: DraggableTree,
      KontextoveMenu,
    },
    props: {
      sekcie: {
        required: true,
        type: Array,
        default () {
          return []
        },
      },
    },
    data () {
      return {}
    },
    methods: {
      onChange(node) {
        const parent = node.parent;
        const children = parent.children;
        const index = children.indexOf(node);
        let moveType;
        let targetNode;

        if (children.length === 1) {
          moveType = 'append';
          targetNode = parent;
        } else if (index === 0) {
          moveType = 'before';
          targetNode = children[1];
        } else {
          moveType = 'after';
          targetNode = children[index - 1];
        }

        axios.patch(`/ucebne-materialy/${node.ucebnica_id}/sekcie/${node.id}`, {
          typ: moveType,
          cielovaSekciaId: targetNode.id,
        });

        if (parent.isRoot) {
          this.$emit('change', this.mutableItems);
        }
      }
    },
    computed: {

    },
    watch: {

    },
    created () {

    }
  }
</script>

<style scoped>

</style>