import ngModule from '../../module';

class Controller {
    constructor($element, $scope, $compile) {
        this.$scope = $scope;
        this.$compile = $compile;
        this.element = $element[0];

        this.element.$ctrl = this;
        this.element.droppable = true;
        this.dropCount = 0;
        this.element.classList.add('vn-droppable');
    }

    $onInit() {
        const transcludeElement = this.element.querySelector('.content');
        const content = angular.element(transcludeElement);

        if (this.item.parent) {
            this.treeview.$transclude(($clone, $scope) => {
                this.$contentScope = $scope;
                $scope.item = this.item;
                content.append($clone);
            });

            this.element.draggable = true;
            this.element.classList.add('vn-draggable');
        } else {
            let template = `<span translate>{{$ctrl.treeview.rootLabel}}</span>`;
            let $clone = this.$compile(template)(this.$scope);
            content.append($clone);
        }
    }

    $onDestroy() {
        if (this.$contentScope)
            this.$contentScope.$destroy();
    }

    dragEnter() {
        this.dropCount++;

        if (element != this.dropping) {
            this.undrop();
            if (element) element.classList.add('dropping');
            this.dropping = element;
        }
    }
}
Controller.$inject = ['$element', '$scope', '$compile'];

ngModule.vnComponent('vnTreeviewChild', {
    template: require('./child.html'),
    controller: Controller,
    bindings: {
        item: '<'
    },
    require: {
        treeview: '^vnTreeview'
    }
});