System.register(["@angular/core", "@angular/cdk/drag-drop", "@angular/cdk/tree", "@angular/platform-browser", "@angular/material/icon", "rxjs", "@stratusjs/runtime/stratus", "lodash", "@agentepsilon/decko", "../core/root.component", "../backend.service", "@stratusjs/angularjs/services/registry", "@stratusjs/core/environment", "@stratusjs/core/events/eventManager", "@angular/common"], function (exports_1, context_1) {
    "use strict";
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var __param = (this && this.__param) || function (paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); }
    };
    var core_1, drag_drop_1, tree_1, platform_browser_1, icon_1, rxjs_1, stratus_1, lodash_1, decko_1, root_component_1, backend_service_1, registry_1, environment_1, eventManager_1, common_1, systemDir, moduleName, min, localDir, TreeComponent;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (drag_drop_1_1) {
                drag_drop_1 = drag_drop_1_1;
            },
            function (tree_1_1) {
                tree_1 = tree_1_1;
            },
            function (platform_browser_1_1) {
                platform_browser_1 = platform_browser_1_1;
            },
            function (icon_1_1) {
                icon_1 = icon_1_1;
            },
            function (rxjs_1_1) {
                rxjs_1 = rxjs_1_1;
            },
            function (stratus_1_1) {
                stratus_1 = stratus_1_1;
            },
            function (lodash_1_1) {
                lodash_1 = lodash_1_1;
            },
            function (decko_1_1) {
                decko_1 = decko_1_1;
            },
            function (root_component_1_1) {
                root_component_1 = root_component_1_1;
            },
            function (backend_service_1_1) {
                backend_service_1 = backend_service_1_1;
            },
            function (registry_1_1) {
                registry_1 = registry_1_1;
            },
            function (environment_1_1) {
                environment_1 = environment_1_1;
            },
            function (eventManager_1_1) {
                eventManager_1 = eventManager_1_1;
            },
            function (common_1_1) {
                common_1 = common_1_1;
            }
        ],
        execute: function () {
            systemDir = '@stratusjs/angular';
            moduleName = 'tree';
            min = !environment_1.cookie('env') ? '.min' : '';
            localDir = `${stratus_1.Stratus.BaseUrl}${boot.configuration.paths[`${systemDir}/*`].replace(/[^/]*$/, '').replace(/\/dist\/$/, '/src/')}`;
            TreeComponent = class TreeComponent extends root_component_1.RootComponent {
                constructor(iconRegistry, sanitizer, backend, ref, elementRef, document) {
                    super();
                    this.iconRegistry = iconRegistry;
                    this.sanitizer = sanitizer;
                    this.backend = backend;
                    this.ref = ref;
                    this.elementRef = elementRef;
                    this.document = document;
                    this.title = moduleName + '_component';
                    this.isInitialized = false;
                    this.isDestroyed = false;
                    this.isStyled = false;
                    this._ = lodash_1.default;
                    this.Stratus = stratus_1.Stratus;
                    this.registry = new registry_1.Registry();
                    this.onChange = new rxjs_1.Subject();
                    this.unsettled = false;
                    this.svgIcons = {};
                    this.dblClickWait = 500;
                    this.dropLists = [];
                    this.dropListIdMap = {};
                    this.dropListMap = {};
                    this.expandedNodeSet = new Set();
                    this.dragging = false;
                    this.expandDelay = 1000;
                    this.dropData = null;
                    this.cdkDropListSortingDisabled = true;
                    this.dropDebug = false;
                    this.treeControl = new tree_1.NestedTreeControl((node) => node.children || []);
                }
                ngOnInit() {
                    this.uid = lodash_1.default.uniqueId(`sa_${lodash_1.default.snakeCase(moduleName)}_component_`);
                    stratus_1.Stratus.Instances[this.uid] = this;
                    this.hydrate(this.elementRef, this.sanitizer, ["title", "uid", "isInitialized", "isDestroyed", "isStyled", "target", "targetSuffix", "id", "manifest", "decouple", "direct", "api", "urlRoot", "type", "property", "_", "Stratus", "registry", "fetched", "data", "collection", "model", "dataSub", "onChange", "subscriber", "unsettled", "svgIcons", "isSingleClick", "dblClickWait", "dropLists", "dropListIdMap", "dropListMap", "expandedNodeSet", "dragging", "expandTimeout", "expandDelay", "dropData", "cdkDropListSortingDisabled", "dropDebug", "tree", "treeMap", "metaMap", "dataSource", "treeControl", "iconRegistry", "sanitizer", "backend", "ref", "elementRef", "document", "ngOnInit", "ngOnDestroy", "refresh", "remove", "removeNode", "nodeIsEqual", "fetchData", "dataDefer", "dataRef", "trackDropLists", "setExpanded", "setExpandedClick", "setExpandedDblClick", "onDragDrop", "onDragMove", "showDragData", "clearDragData", "buildNodePatch", "getSvg", "addSvgIcon", "hydrate", "disableRefresh", "stagger", "reloading"]);
                    stratus_1.Stratus.Internals.CssLoader(`${localDir}/${moduleName}/${moduleName}.component${min}.css`)
                        .then(() => {
                        this.isStyled = true;
                        this.refresh();
                    })
                        .catch((err) => {
                        console.warn('Issue detected in CSS Loader for Component:', this);
                        console.error(err);
                        this.isStyled = true;
                        this.refresh();
                    });
                    lodash_1.default.forEach({
                        tree_check: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/check.svg`,
                        tree_add: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/add.svg`,
                        tree_delete: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/delete.svg`,
                        tree_edit: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/edit.svg`,
                        tree_visibility: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/visibility.svg`,
                    }, (value, key) => this.iconRegistry.addSvgIcon(key, this.sanitizer.bypassSecurityTrustResourceUrl(value)).getNamedSvgIcon(key));
                    this.fetchData()
                        .then(data => {
                        if (!data || !(data instanceof eventManager_1.EventManager)) {
                            console.warn('Unable to bind data from Registry!');
                            return;
                        }
                        const onDataChange = () => {
                            if (this.unsettled || !data.completed) {
                                return;
                            }
                            this.dataDefer(this.subscriber);
                            this.refresh();
                        };
                        data.on('change', onDataChange);
                        onDataChange();
                        data.on('add', (event, model) => {
                            let modelCompleted = false;
                            const onModelChange = () => {
                                if (!model.completed) {
                                    return;
                                }
                                if (modelCompleted) {
                                    return;
                                }
                                modelCompleted = true;
                                if (!(model.getIdentifier() in this.treeMap)) {
                                    model.meta.set('postPersist', true);
                                    return;
                                }
                                const node = this.treeMap[model.getIdentifier()];
                                if (!node.meta.component || !('openDialog' in node.meta.component)) {
                                    model.meta.set('postPersist', true);
                                    return;
                                }
                                node.meta.component.openDialog();
                            };
                            model.on('change', onModelChange);
                            onModelChange();
                        });
                    });
                    this.dataSub = new rxjs_1.Observable((subscriber) => this.dataDefer(subscriber));
                    this.dropListIdMap[`${this.uid}_parent_drop_list`] = true;
                    this.trackDropLists();
                    this.isInitialized = true;
                    this.refresh();
                }
                ngOnDestroy() {
                    this.isDestroyed = true;
                }
                refresh() {
                    if (this.isDestroyed) {
                        return new Promise(resolve => resolve());
                    }
                    lodash_1.default.forEach(this.metaMap, (meta) => {
                        if (!meta.component || !('refresh' in meta.component)) {
                            return;
                        }
                        meta.component.refresh();
                    });
                    return super.refresh();
                }
                remove(model) {
                }
                removeNode(list, node) {
                    const index = list.indexOf(node);
                    if (index === -1) {
                        return false;
                    }
                    list.splice(index, 1);
                    return true;
                }
                nodeIsEqual(node, other) {
                    if (!node || !other) {
                        return node === other;
                    }
                    return node.id === other.id;
                }
                async fetchData() {
                    if (this.fetched) {
                        return this.fetched;
                    }
                    return this.fetched = this.registry.fetch(stratus_1.Stratus.Select(this.elementRef.nativeElement), this);
                }
                dataDefer(subscriber) {
                    this.subscriber = this.subscriber || subscriber;
                    if (!this.subscriber || !this.collection || !this.collection.completed) {
                        setTimeout(() => {
                            this.dataDefer(subscriber);
                        }, 500);
                        return;
                    }
                    const tree = this.dataRef(true);
                    if (tree && tree.length) {
                        subscriber.next(tree);
                        return;
                    }
                    setTimeout(() => this.dataDefer(subscriber), 200);
                }
                dataRef(force = false) {
                    if (!this.collection) {
                        return [];
                    }
                    if (!force && this.tree && this.tree.length > 0) {
                        return this.tree;
                    }
                    let models = this.collection.models;
                    if (!models || !lodash_1.default.isArray(models) || !models.length) {
                        return [];
                    }
                    models = lodash_1.default.sortBy(models, ['data.priority']);
                    this.metaMap = this.metaMap || {};
                    this.treeMap = {};
                    this.tree = [];
                    lodash_1.default.forEach(models, (model) => {
                        const modelId = lodash_1.default.get(model, 'data.id');
                        const parentId = lodash_1.default.get(model, 'data.nestParent.id');
                        this.dropListIdMap[`${this.uid}_node_${modelId}_drop_list`] = true;
                        if (!lodash_1.default.has(this.metaMap, modelId)) {
                            this.metaMap[modelId] = {
                                id: modelId,
                                expanded: true
                            };
                        }
                        if (!lodash_1.default.has(this.treeMap, modelId)) {
                            this.treeMap[modelId] = {
                                id: modelId,
                                model,
                                children: [],
                                meta: this.metaMap[modelId]
                            };
                        }
                        this.treeMap[modelId].model = model;
                        this.treeMap[modelId].meta = this.metaMap[modelId];
                        if (parentId) {
                            if (!lodash_1.default.has(this.treeMap, parentId)) {
                                this.treeMap[parentId] = {
                                    id: parentId,
                                    model: null,
                                    children: [],
                                    meta: null
                                };
                            }
                            this.treeMap[parentId].children.push(this.treeMap[modelId]);
                        }
                        else {
                            this.tree.push(this.treeMap[modelId]);
                        }
                    });
                    this.trackDropLists();
                    return this.tree;
                }
                trackDropLists() {
                    this.dropLists = [];
                    lodash_1.default.forEach(this.dropListIdMap, (value, key) => {
                        if (!value) {
                            return;
                        }
                        const cached = key in this.dropListMap;
                        const element = cached ? this.dropListMap[key] : document.getElementById(key);
                        if (!element) {
                            return;
                        }
                        this.dropLists.push(key);
                        if (cached) {
                            return;
                        }
                        this.dropListMap[key] = element;
                    });
                }
                setExpanded(expanded) {
                    if (!this.metaMap || !lodash_1.default.size(this.metaMap)) {
                        return;
                    }
                    lodash_1.default.forEach(this.metaMap, (nodeMeta) => {
                        nodeMeta.expanded = expanded;
                    });
                    this.refresh();
                }
                setExpandedClick(expanded) {
                    this.isSingleClick = true;
                    setTimeout(() => {
                        if (!this.isSingleClick) {
                            return;
                        }
                        this.setExpanded(expanded);
                    }, this.dblClickWait);
                }
                setExpandedDblClick(expanded) {
                    this.isSingleClick = false;
                    this.setExpanded(expanded);
                }
                onDragDrop(event) {
                    if (!event.isPointerOverContainer) {
                        return;
                    }
                    const targetNode = event.item.data;
                    if (!targetNode) {
                        return;
                    }
                    let parentNode = event.container.data;
                    const pastParentNode = event.previousContainer.data;
                    const tree = parentNode ? parentNode.children : this.dataRef();
                    if (!tree) {
                        return;
                    }
                    this.unsettled = true;
                    const targetDropNode = (this.dropData.targetId && this.dropData.targetId in this.treeMap) ?
                        this.treeMap[lodash_1.default.toNumber(this.dropData.targetId)] : null;
                    if (environment_1.cookie('env') && this.dropDebug) {
                        console.group('onDragDrop()');
                        lodash_1.default.forEach([
                            `model drop: ${targetNode.model.get('name')}`,
                            `list shift: ${event.container.element.nativeElement.id} -> ${event.previousContainer.element.nativeElement.id}`,
                            `index change (event): ${event.previousIndex} -> ${event.currentIndex}`,
                            `current priority: ${targetNode.model.get('priority')}`,
                            `target drop action: ${this.dropData.action}`,
                        ], (message) => console.log(message));
                    }
                    if (targetDropNode && !this.nodeIsEqual(parentNode, targetDropNode)) {
                        if (environment_1.cookie('env') && this.dropDebug) {
                            console.log(`target drop node differs: ${targetDropNode.id} -> ${targetDropNode.model.get('name')}`);
                            console.log('target drop node is the same as target node:', targetNode.id === targetDropNode.id);
                        }
                        if (targetNode.id !== targetDropNode.id) {
                            switch (this.dropData.action) {
                                case 'before':
                                case 'after':
                                    const nestParentId = targetDropNode.model.get('nestParent.id');
                                    const nestParent = (nestParentId && nestParentId in this.treeMap) ? this.treeMap[nestParentId] : null;
                                    parentNode = nestParent;
                                    break;
                                case 'inside':
                                    parentNode = targetDropNode;
                                    break;
                            }
                        }
                        if (environment_1.cookie('env') && this.dropDebug) {
                            console.log('target drop node selected:', parentNode ? `${parentNode.id} -> ${parentNode.model.get('name')}` : 'none');
                        }
                    }
                    if (!this.nodeIsEqual(parentNode, pastParentNode)) {
                        if (parentNode) {
                            switch (this.dropData.action) {
                                case 'before':
                                case 'after':
                                    let targetIndex = parentNode.children.findIndex((n) => n.id === targetNode.id);
                                    if (this.dropData.action === 'after') {
                                        targetIndex++;
                                    }
                                    parentNode.children.splice(targetIndex, 0, targetNode);
                                    break;
                                case 'inside':
                                    parentNode.children.push(targetNode);
                                    break;
                            }
                            parentNode.meta.expanded = true;
                        }
                        if (pastParentNode) {
                            this.removeNode(pastParentNode.children, targetNode);
                        }
                        targetNode.model.set('nestParent', this.buildNodePatch(parentNode));
                        if (environment_1.cookie('env') && this.dropDebug) {
                            console.log(`new parent: ${targetNode.model.get('nestParent.name') || null}`);
                        }
                    }
                    const branch = parentNode ? parentNode.children : tree;
                    let targetDropIndex = event.currentIndex;
                    if (this.cdkDropListSortingDisabled) {
                        targetDropIndex = null;
                        switch (this.dropData.action) {
                            case 'before':
                            case 'after':
                                targetDropIndex = branch.findIndex((n) => n.id === targetDropNode.id);
                                if (this.dropData.action === 'after') {
                                    targetDropIndex++;
                                }
                                if (environment_1.cookie('env') && this.dropDebug) {
                                    console.log('index change (drop node):', `${event.previousIndex} -> ${targetDropIndex}`);
                                }
                                break;
                        }
                    }
                    if (lodash_1.default.isNumber(targetDropIndex)) {
                        drag_drop_1.moveItemInArray(branch, event.previousIndex, targetDropIndex);
                        let priority = 0;
                        lodash_1.default.forEach(branch, (node) => {
                            if (!node.model || !node.model.set) {
                                return;
                            }
                            node.model.set('priority', priority++);
                        });
                        if (environment_1.cookie('env') && this.dropDebug) {
                            console.log('new priority:', targetNode.model.get('priority'));
                        }
                    }
                    if (environment_1.cookie('env') && this.dropDebug) {
                        console.log(`new parent: ${targetNode.model.get('nestParent.name') || null}`);
                        console.groupEnd();
                    }
                    targetNode.model.save();
                    this.unsettled = false;
                }
                onDragMove(event) {
                    const e = this.document.elementFromPoint(event.pointerPosition.x, event.pointerPosition.y);
                    if (!e) {
                        this.clearDragData();
                        return;
                    }
                    const containerClass = 'tree-node-content';
                    const container = e.classList.contains(containerClass) ? e : e.closest(`.${containerClass}`);
                    if (!container) {
                        this.clearDragData();
                        return;
                    }
                    this.dropData = {
                        targetId: container.getAttribute('data-id')
                    };
                    const targetRect = container.getBoundingClientRect();
                    const oneThird = targetRect.height / 3;
                    if (event.pointerPosition.y - targetRect.top < oneThird) {
                        this.dropData.action = 'before';
                    }
                    else if (event.pointerPosition.y - targetRect.top > 2 * oneThird) {
                        this.dropData.action = 'after';
                    }
                    else {
                        this.dropData.action = 'inside';
                    }
                    this.showDragData();
                }
                showDragData() {
                    this.clearDragData();
                    if (!this.dropData) {
                        return;
                    }
                    this.document.getElementById(`node-${this.dropData.targetId}`).classList.add(`drop-${this.dropData.action}`);
                }
                clearDragData(dropped = false) {
                    if (dropped) {
                        this.dropData = null;
                    }
                    this.document
                        .querySelectorAll('.drop-before')
                        .forEach(element => element.classList.remove('drop-before'));
                    this.document
                        .querySelectorAll('.drop-after')
                        .forEach(element => element.classList.remove('drop-after'));
                    this.document
                        .querySelectorAll('.drop-inside')
                        .forEach(element => element.classList.remove('drop-inside'));
                }
                buildNodePatch(node = null) {
                    if (!node || !node.model) {
                        return null;
                    }
                    const nodePatch = {};
                    lodash_1.default.forEach([
                        'id',
                        'name'
                    ], (key) => {
                        const value = node.model.get(key);
                        if (!value) {
                            return;
                        }
                        lodash_1.default.set(nodePatch, key, value);
                    });
                    return nodePatch;
                }
                getSvg(url, options) {
                    const uid = this.addSvgIcon(url, options);
                    return new rxjs_1.Observable((subscriber) => {
                        this.iconRegistry
                            .getNamedSvgIcon(uid)
                            .subscribe({
                            error(err) {
                                console.error(`getSvg(${url}): ${err}`);
                            },
                            complete() {
                                subscriber.next(uid);
                            }
                        });
                    });
                }
                addSvgIcon(url, options) {
                    if (url in this.svgIcons) {
                        return this.svgIcons[url];
                    }
                    if (!options) {
                        options = {};
                    }
                    const uid = this.svgIcons[url] = lodash_1.default.uniqueId('selector_svg');
                    this.iconRegistry.addSvgIcon(uid, this.sanitizer.bypassSecurityTrustResourceUrl(url), options);
                    return uid;
                }
            };
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], TreeComponent.prototype, "target", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], TreeComponent.prototype, "targetSuffix", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Number)
            ], TreeComponent.prototype, "id", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], TreeComponent.prototype, "manifest", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], TreeComponent.prototype, "decouple", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], TreeComponent.prototype, "direct", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Object)
            ], TreeComponent.prototype, "api", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], TreeComponent.prototype, "urlRoot", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], TreeComponent.prototype, "type", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], TreeComponent.prototype, "property", void 0);
            __decorate([
                decko_1.debounce(50),
                __metadata("design:type", Function),
                __metadata("design:paramtypes", [Object]),
                __metadata("design:returntype", void 0)
            ], TreeComponent.prototype, "onDragMove", null);
            TreeComponent = __decorate([
                core_1.Component({
                    selector: `sa-${moduleName}`,
                    templateUrl: `${localDir}/${moduleName}/${moduleName}.component${min}.html`,
                }),
                __param(5, core_1.Inject(common_1.DOCUMENT)),
                __metadata("design:paramtypes", [icon_1.MatIconRegistry,
                    platform_browser_1.DomSanitizer,
                    backend_service_1.BackendService,
                    core_1.ChangeDetectorRef,
                    core_1.ElementRef,
                    Document])
            ], TreeComponent);
            exports_1("TreeComponent", TreeComponent);
        }
    };
});

//# sourceMappingURL=tree.component.js.map
