System.register(["@angular/core", "@angular/forms", "@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", "@stratusjs/core/datastore/xhr"], 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, forms_1, drag_drop_1, rxjs_1, platform_browser_1, icon_1, stratus_1, lodash_1, environment_1, root_component_1, registry_1, eventManager_1, xhr_1, systemDir, moduleName, min, localDir, has, SelectorComponent;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (forms_1_1) {
                forms_1 = forms_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 (xhr_1_1) {
                xhr_1 = xhr_1_1;
            }
        ],
        execute: function () {
            systemDir = '@stratusjs/angular';
            moduleName = '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));
            SelectorComponent = class SelectorComponent extends root_component_1.RootComponent {
                constructor(iconRegistry, sanitizer, ref, elementRef) {
                    super();
                    this.iconRegistry = iconRegistry;
                    this.sanitizer = sanitizer;
                    this.ref = ref;
                    this.elementRef = elementRef;
                    this.title = moduleName + '_component';
                    this._ = lodash_1.default;
                    this.has = has;
                    this.log = console.log;
                    this.Stratus = stratus_1.Stratus;
                    this.selectCtrl = new forms_1.FormControl();
                    this.registry = new registry_1.Registry();
                    this.onChange = new rxjs_1.Subject();
                    this.svgIcons = {};
                    this.styled = false;
                    this.empty = 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));
                    lodash_1.default.forEach({
                        selector_delete: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/delete.svg`,
                        selector_status: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/visibility.svg`,
                        selector_edit: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/edit.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", "ignorePriority", "_", "has", "log", "Stratus", "selectCtrl", "registry", "fetched", "data", "collection", "model", "dataSub", "onChange", "subscriber", "svgIcons", "styled", "empty", "iconRegistry", "sanitizer", "ref", "elementRef", "drop", "goToUrl", "toggleStatus", "remove", "fetchData", "dataDefer", "dataRef", "onDataChange", "prioritize", "getSvg", "addSvgIcon", "hydrate", "disableRefresh", "stagger", "reloading", "refresh", "ngOnDestroy"]);
                    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;
                    }
                    drag_drop_1.moveItemInArray(models, event.previousIndex, event.currentIndex);
                    if (!this.ignorePriority) {
                        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');
                }
                toggleStatus(model) {
                    const statusOriginal = model.status;
                    model.status = statusOriginal === 1 ? 0 : 1;
                    const xhr = new xhr_1.XHR({
                        method: 'PUT',
                        url: '/Api/Content/' + model.id,
                        data: {
                            route: {},
                            meta: {},
                            payload: {
                                status: model.status
                            }
                        },
                        type: 'application/json'
                    });
                    xhr.send()
                        .then((response) => {
                        if (!lodash_1.default.isObject(response) || lodash_1.default.get(response, 'meta.status[0].code') !== 'SUCCESS') {
                            console.error('error[toggleStatus]:', response);
                            model.status = statusOriginal;
                            this.refresh();
                            return;
                        }
                        console.log('success[toggleStatus]:', response);
                    })
                        .catch((error) => {
                        console.error('error[toggleStatus]:', error);
                        model.status = statusOriginal;
                        this.refresh();
                    });
                    return;
                }
                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');
                }
                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;
                    }
                    if (!this.ignorePriority) {
                        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('selector_svg');
                    this.iconRegistry.addSvgIcon(uid, this.sanitizer.bypassSecurityTrustResourceUrl(url), options);
                    return uid;
                }
            };
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "target", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "targetSuffix", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Number)
            ], SelectorComponent.prototype, "id", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], SelectorComponent.prototype, "manifest", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], SelectorComponent.prototype, "decouple", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], SelectorComponent.prototype, "direct", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Object)
            ], SelectorComponent.prototype, "api", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "urlRoot", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "type", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "property", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", String)
            ], SelectorComponent.prototype, "endpoint", void 0);
            __decorate([
                core_1.Input(),
                __metadata("design:type", Boolean)
            ], SelectorComponent.prototype, "ignorePriority", void 0);
            SelectorComponent = __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])
            ], SelectorComponent);
            exports_1("SelectorComponent", SelectorComponent);
        }
    };
});

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