import Vue from 'vue/dist/vue'
import BuilderClient from "../api/BuilderClient";

export default new Vue({
    methods: {
        prepareTree(brick) {

            brick = this._prepareBrick(brick);

            if (brick.children.length > 0) {
                for (var i = 0; i < brick.children.length; i++) {
                    brick.children[i] = this.prepareTree(brick.children[i]);
                }
            }

            return brick;
        },
        _prepareBrick(brick) {
            brick.draggableGroup = 'allowed_children:' + brick.allowedChildren;
            brick.canReceiveCurrentDrag = false;
            brick.vueComponent = null;

            return brick;
        },
        filter(brick, callback, stack) {
            if (typeof stack === 'undefined') {
                stack = [];
            }

            var test = callback(brick);
            if (typeof test !== 'undefined' && test) {
                stack.push(brick);
            }

            if (brick.children.length > 0) {
                for (var i = 0; i < brick.children.length; i++) {
                    this.filter(brick.children[i], callback, stack);
                }
            }

            return stack;
        },
        _findBrick(brick, treeBrick, mode, parent = null) {
            if (typeof mode === 'undefined') {
                mode = 'default'; // default search for brick itself
            }

            var allowedModes = ['default', 'parent'];
            if (allowedModes.indexOf(mode) === -1) {
                return;
            }

            if (brick.id === treeBrick.id) {
                return mode === 'parent' ? parent : brick;
            }

            if (treeBrick.children.length > 0) {
                for (var i = 0; i < treeBrick.children.length; i++) {
                    var found = this._findBrick(brick, treeBrick.children[i], mode, treeBrick)
                    if (found !== false) {
                        return found;
                    }
                }
            }

            return false;
        },
        findBrick(brick, treeBrick) {
            return this._findBrick(brick, treeBrick);
        },
        findBrickParent(childBrick, treeBrick) {
            return this._findBrick(childBrick, treeBrick, 'parent');
        },
        removeBrickChild(brick, childBrick) {
            for (var i = 0; i < brick.children.length; i++) {
                var child = brick.children[i];

                if (child.id === childBrick.id) {
                    Vue.delete(brick.children, i);

                    return true;
                }
            }

            return false;
        },
    },
})
