System.register(["@angular/core", "@angular/cdk/drag-drop", "rxjs", "@angular/platform-browser", "@angular/material/icon", "@stratusjs/runtime/stratus", "lodash", "@stratusjs/core/environment", "../core/root.component", "@stratusjs/angularjs/services/registry", "@stratusjs/core/events/eventManager", "@angular/cdk/scrolling"], 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 core_1, drag_drop_1, rxjs_1, platform_browser_1, icon_1, stratus_1, lodash_1, environment_1, root_component_1, registry_1, eventManager_1, scrolling_1, systemDir, moduleName, min, localDir, has, MediaSelectorComponent;
    var __moduleName = context_1 && context_1.id;
    function __indexOf(collection, node) {
        return Array.prototype.indexOf.call(collection, node);
    }
    function __isTouchEvent(event) {
        return event.type.startsWith('touch');
    }
    function __isInsideDropListClientRect(dropList, x, y) {
        const { top, bottom, left, right } = dropList.element.nativeElement.getBoundingClientRect();
        return y >= top && y <= bottom && x >= left && x <= right;
    }
    return {
        setters: [
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (drag_drop_1_1) {
                drag_drop_1 = drag_drop_1_1;
            },
            function (rxjs_1_1) {
                rxjs_1 = rxjs_1_1;
            },
            function (platform_browser_1_1) {
                platform_browser_1 = platform_browser_1_1;
            },
            function (icon_1_1) {
                icon_1 = icon_1_1;
            },
            function (stratus_1_1) {
                stratus_1 = stratus_1_1;
            },
            function (lodash_1_1) {
                lodash_1 = lodash_1_1;
            },
            function (environment_1_1) {
                environment_1 = environment_1_1;
            },
            function (root_component_1_1) {
                root_component_1 = root_component_1_1;
            },
            function (registry_1_1) {
                registry_1 = registry_1_1;
            },
            function (eventManager_1_1) {
                eventManager_1 = eventManager_1_1;
            },
            function (scrolling_1_1) {
                scrolling_1 = scrolling_1_1;
            }
        ],
        execute: function () {
            systemDir = '@stratusjs/angular';
            moduleName = 'media-selector';
            min = !environment_1.cookie('env') ? '.min' : '';
            localDir = `${stratus_1.Stratus.BaseUrl}${boot.configuration.paths[`${systemDir}/*`].replace(/[^/]*$/, '').replace(/\/dist\/$/, '/src/')}`;
            has = (object, path) => lodash_1.default.has(object, path) && !lodash_1.default.isEmpty(lodash_1.default.get(object, path));
            MediaSelectorComponent = class MediaSelectorComponent extends root_component_1.RootComponent {
                constructor(iconRegistry, sanitizer, ref, elementRef, viewportRuler) {
                    super();
                    this.iconRegistry = iconRegistry;
                    this.sanitizer = sanitizer;
                    this.ref = ref;
                    this.elementRef = elementRef;
                    this.viewportRuler = viewportRuler;
                    this.title = moduleName + '_component';
                    this._ = lodash_1.default;
                    this.has = has;
                    this.log = console.log;
                    this.Stratus = stratus_1.Stratus;
                    this.registry = new registry_1.Registry();
                    this.onChange = new rxjs_1.Subject();
                    this.svgIcons = {};
                    this.styled = false;
                    this.empty = false;
                    this.libraryDisplay = false;
                    this.isSelector = true;
                    this.isGrid = true;
                    this.enterPredicate = (drag, drop) => {
                        if (drop === this.placeholder) {
                            return true;
                        }
                        if (environment_1.cookie('env')) {
                            console.log('entering predicate...');
                        }
                        if (drop !== this.activeContainer) {
                            return false;
                        }
                        const placeholderElement = this.placeholder.element.nativeElement;
                        const sourceElement = drag.dropContainer.element.nativeElement;
                        const dropElement = drop.element.nativeElement;
                        const dragIndex = __indexOf(dropElement.parentElement.children, (this.sourceList ? placeholderElement : sourceElement));
                        const dropIndex = __indexOf(dropElement.parentElement.children, dropElement);
                        if (!this.sourceList) {
                            this.sourceIndex = dragIndex;
                            this.sourceList = drag.dropContainer;
                            placeholderElement.style.width = `${sourceElement.clientWidth}px`;
                            placeholderElement.style.height = `${sourceElement.clientHeight}px`;
                            sourceElement.parentElement.removeChild(sourceElement);
                        }
                        this.targetIndex = dropIndex;
                        this.targetList = drop;
                        if (environment_1.cookie('env')) {
                            console.log('predicate:', this.sourceIndex, '->', this.targetIndex);
                        }
                        placeholderElement.style.display = '';
                        dropElement.parentElement.insertBefore(placeholderElement, dropIndex > dragIndex ? dropElement.nextSibling : dropElement);
                        this.placeholder._dropListRef.enter(drag._dragRef, drag.element.nativeElement.offsetLeft, drag.element.nativeElement.offsetTop);
                        return false;
                    };
                    this.uid = lodash_1.default.uniqueId(`sa_${lodash_1.default.snakeCase(moduleName)}_component_`);
                    stratus_1.Stratus.Instances[this.uid] = this;
                    this.dataSub = new rxjs_1.Observable(subscriber => this.dataDefer(subscriber));
                    this.targetList = null;
                    this.sourceList = null;
                    lodash_1.default.forEach({
                        media_selector_add: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/add.svg`,
                        media_selector_clear: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/clear.svg`,
                        media_selector_delete: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/delete.svg`,
                        media_selector_edit: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/edit.svg`,
                        media_selector_info: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/info.svg`,
                        media_selector_image: `${stratus_1.Stratus.BaseUrl}sitetheorymedia/images/mediaTypeIcons/media-icon-image.svg`,
                        media_selector_video: `${stratus_1.Stratus.BaseUrl}sitetheorymedia/images/mediaTypeIcons/media-icon-video.svg`,
                        media_selector_audio: `${stratus_1.Stratus.BaseUrl}sitetheorymedia/images/mediaTypeIcons/media-icon-audio.svg`,
                        media_selector_document: `${stratus_1.Stratus.BaseUrl}sitetheorymedia/images/mediaTypeIcons/media-icon-document.svg`
                    }, (value, key) => iconRegistry.addSvgIcon(key, sanitizer.bypassSecurityTrustResourceUrl(value)).getNamedSvgIcon(key));
                    stratus_1.Stratus.Internals.CssLoader(`${localDir}${moduleName}/${moduleName}.component${min}.css`)
                        .then(() => {
                        this.styled = true;
                        this.refresh();
                    })
                        .catch((err) => {
                        console.warn('Issue detected in CSS Loader for Component:', this);
                        console.error(err);
                        this.styled = true;
                        this.refresh();
                    });
                    this.hydrate(elementRef, sanitizer, ["title", "uid", "target", "targetSuffix", "id", "manifest", "decouple", "direct", "api", "urlRoot", "type", "property", "endpoint", "_", "has", "log", "Stratus", "registry", "fetched", "data", "collection", "model", "dataSub", "onChange", "subscriber", "eventID", "svgIcons", "styled", "empty", "libraryDisplay", "isSelector", "isGrid", "listGroup", "placeholder", "targetList", "targetIndex", "sourceList", "sourceIndex", "activeContainer", "iconRegistry", "sanitizer", "ref", "elementRef", "viewportRuler", "drop", "moveModel", "goToUrl", "remove", "fetchData", "dataDefer", "dataRef", "onDataChange", "prioritize", "getSvg", "addSvgIcon", "toggleLibrary", "showDetails", "deleteMedia", "removeFromSelected", "dragEntered", "move", "moveItemInGrid", "enterPredicate", "getPointerPositionOnPage", "hydrate", "disableRefresh", "stagger", "reloading", "refresh", "ngOnDestroy"]);
                    this.eventID = `${this.target}:${this.id}:${this.property}`;
                    this.fetchData()
                        .then(data => {
                        if (!data || !(data instanceof eventManager_1.EventManager)) {
                            console.warn('Unable to bind data from Registry!');
                            return;
                        }
                        const onDataChange = () => {
                            if (!data.completed) {
                                return;
                            }
                            this.dataDefer(this.subscriber);
                            this.prioritize();
                            this.refresh();
                        };
                        data.on('change', onDataChange);
                        onDataChange();
                    });
                }
                drop(event) {
                    const models = this.dataRef();
                    if (!models || !models.length) {
                        return;
                    }
                    if (environment_1.cookie('env')) {
                        console.log('drop:', event.previousContainer.id, event.container.id);
                    }
                    if (!this.isGrid || !this.moveItemInGrid(models)) {
                        if (this.isGrid && environment_1.cookie('env')) {
                            console.warn('moving item in grid failed. attempting fallback.');
                        }
                        drag_drop_1.moveItemInArray(models, event.previousIndex, event.currentIndex);
                    }
                    let priority = 0;
                    lodash_1.default.forEach(models, (model) => model.priority = priority++);
                    this.model.trigger('change');
                }
                moveModel(previousIndex, currentIndex) {
                    const models = this.dataRef();
                    if (!models || !models.length) {
                        return;
                    }
                    drag_drop_1.moveItemInArray(models, previousIndex, currentIndex);
                    let priority = 0;
                    lodash_1.default.forEach(models, (model) => model.priority = priority++);
                    this.model.trigger('change');
                }
                goToUrl(model) {
                    if (!model || !model.contentType) {
                        console.error('unable to execute goToUrl() because a valid model content was not provided.');
                        return;
                    }
                    window.open(model.contentType.editUrl + '?id=' + model.id, '_blank');
                }
                remove(model) {
                    const models = this.dataRef();
                    if (!models || !models.length) {
                        console.error('unable to remove model from selection:', models);
                        this.refresh();
                        return;
                    }
                    let index = models.indexOf(model);
                    if (index === -1) {
                        const mirrorModels = models
                            .map((m) => model.id === m.id ? m : null)
                            .filter((m) => m);
                        if (lodash_1.default.isArray(mirrorModels) && mirrorModels.length) {
                            index = models.indexOf(lodash_1.default.first(mirrorModels));
                        }
                    }
                    if (index === -1) {
                        console.error('unable to find model:', model, 'in selection:', models);
                        return;
                    }
                    models.splice(index, 1);
                    this.model.trigger('change');
                    this.removeFromSelected(model.id);
                }
                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.model || !this.model.completed) {
                        setTimeout(() => {
                            this.dataDefer(subscriber);
                        }, 500);
                        return;
                    }
                    const models = this.dataRef();
                    this.empty = !models.length;
                    this.subscriber.next(models);
                    this.refresh();
                }
                dataRef() {
                    if (!this.model) {
                        return [];
                    }
                    const models = this.model.get(this.property);
                    if (!models || !lodash_1.default.isArray(models)) {
                        return [];
                    }
                    return models;
                }
                onDataChange() {
                    this.prioritize();
                    this.dataDefer(this.subscriber);
                    this.refresh();
                }
                prioritize() {
                    const models = this.dataRef();
                    if (!models || !models.length) {
                        return;
                    }
                    let priority = 0;
                    lodash_1.default.forEach(models, (model) => model.priority = priority++);
                }
                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('media_selector_svg');
                    this.iconRegistry.addSvgIcon(uid, this.sanitizer.bypassSecurityTrustResourceUrl(url), options);
                    return uid;
                }
                toggleLibrary() {
                    this.libraryDisplay = !this.libraryDisplay;
                    stratus_1.Stratus.Environment.trigger(this.eventID, 'toggleLibrary');
                    stratus_1.Stratus.Environment.trigger(`${this.eventID}:toggleLibrary`, this.libraryDisplay);
                }
                showDetails(model) {
                    stratus_1.Stratus.Environment.trigger(this.eventID, 'showDetails');
                    stratus_1.Stratus.Environment.trigger(`${this.eventID}:showDetails`, model);
                }
                deleteMedia(model) {
                    stratus_1.Stratus.Environment.trigger(this.eventID, 'deleteMedia');
                    stratus_1.Stratus.Environment.trigger(`${this.eventID}:deleteMedia`, model);
                }
                removeFromSelected(model) {
                    stratus_1.Stratus.Environment.trigger(this.eventID, 'removeFromSelected');
                    stratus_1.Stratus.Environment.trigger(`${this.eventID}:removeFromSelected`, model);
                }
                dragEntered(event) {
                    const models = this.dataRef();
                    if (!models || !models.length) {
                        return;
                    }
                    const drag = event.item;
                    const dropList = event.container;
                    const dragIndex = drag.data;
                    const dropIndex = dropList.data;
                    const placeholderContainer = dropList.element.nativeElement;
                    const placeholderElement = placeholderContainer.querySelector('.cdk-drag-placeholder');
                    placeholderContainer.removeChild(placeholderElement);
                    placeholderContainer.parentElement.insertBefore(placeholderElement, placeholderContainer);
                    if (environment_1.cookie('env')) {
                        console.log('media move:', dragIndex, '->', dropIndex);
                    }
                    drag_drop_1.moveItemInArray(models, dragIndex, dropIndex);
                    let priority = 0;
                    lodash_1.default.forEach(models, (model) => model.priority = priority++);
                    this.model.trigger('change');
                }
                move(event) {
                    const point = this.getPointerPositionOnPage(event.event);
                    if (lodash_1.default.isUndefined(this.listGroup) || !this.listGroup) {
                        console.warn('this.listGroup does not exist:', this);
                        return;
                    }
                    if (lodash_1.default.isUndefined(this.listGroup._items)) {
                        console.warn('this.listGroup._items does not exist:', this.listGroup);
                        return;
                    }
                    this.listGroup._items.forEach((dropList) => {
                        if (!__isInsideDropListClientRect(dropList, point.x, point.y)) {
                            return;
                        }
                        this.activeContainer = dropList;
                    });
                }
                moveItemInGrid(collection) {
                    if (environment_1.cookie('env')) {
                        console.log('moveItemInGrid:', collection);
                    }
                    if (!this.targetList) {
                        return false;
                    }
                    const placeholderElement = this.placeholder.element.nativeElement;
                    const parentElement = placeholderElement.parentElement;
                    placeholderElement.style.display = 'none';
                    parentElement.removeChild(placeholderElement);
                    parentElement.appendChild(placeholderElement);
                    parentElement.insertBefore(this.sourceList.element.nativeElement, parentElement.children[this.sourceIndex]);
                    this.targetList = null;
                    this.sourceList = null;
                    if (this.sourceIndex === this.targetIndex) {
                        return false;
                    }
                    drag_drop_1.moveItemInArray(collection, this.sourceIndex, this.targetIndex);
                    return true;
                }
                getPointerPositionOnPage(event) {
                    const point = __isTouchEvent(event) ? (event.touches[0] || event.changedTouches[0]) : event;
                    const scrollPosition = this.viewportRuler.getViewportScrollPosition();
                    return {
                        x: point.pageX - scrollPosition.left,
                        y: point.pageY - scrollPosition.top
                    };
                }
            };
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "target", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "targetSuffix", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Number)
            ], MediaSelectorComponent.prototype, "id", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], MediaSelectorComponent.prototype, "manifest", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], MediaSelectorComponent.prototype, "decouple", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], MediaSelectorComponent.prototype, "direct", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Object)
            ], MediaSelectorComponent.prototype, "api", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "urlRoot", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "type", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "property", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], MediaSelectorComponent.prototype, "endpoint", void 0);
            __decorate([
                core_1.ViewChild(drag_drop_1.CdkDropListGroup),
                __metadata("design:type", drag_drop_1.CdkDropListGroup)
            ], MediaSelectorComponent.prototype, "listGroup", void 0);
            __decorate([
                core_1.ViewChild(drag_drop_1.CdkDropList),
                __metadata("design:type", drag_drop_1.CdkDropList)
            ], MediaSelectorComponent.prototype, "placeholder", void 0);
            MediaSelectorComponent = __decorate([
                core_1.Component({
                    selector: `sa-${moduleName}`,
                    templateUrl: `${localDir}/${moduleName}/${moduleName}.component${min}.html`,
                }),
                __metadata("design:paramtypes", [icon_1.MatIconRegistry,
                    platform_browser_1.DomSanitizer,
                    core_1.ChangeDetectorRef,
                    core_1.ElementRef,
                    scrolling_1.ViewportRuler])
            ], MediaSelectorComponent);
            exports_1("MediaSelectorComponent", MediaSelectorComponent);
        }
    };
});

//# sourceMappingURL=media-selector.component.js.map
