System.register(["@angular/core", "@angular/forms", "@angular/material/dialog", "@angular/material/snack-bar", "rxjs", "rxjs/operators", "lodash", "@stratusjs/runtime/stratus", "@stratusjs/core/environment", "../backend.service", "@stratusjs/angularjs/services/model", "../core/responsive.component", "@angular/material/icon", "@angular/platform-browser"], 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, forms_1, dialog_1, snack_bar_1, rxjs_1, operators_1, lodash_1, stratus_1, environment_1, backend_service_1, model_1, responsive_component_1, icon_1, platform_browser_1, systemDir, moduleName, parentModuleName, min, localDir, LinkDialogComponent;
    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 (dialog_1_1) {
                dialog_1 = dialog_1_1;
            },
            function (snack_bar_1_1) {
                snack_bar_1 = snack_bar_1_1;
            },
            function (rxjs_1_1) {
                rxjs_1 = rxjs_1_1;
            },
            function (operators_1_1) {
                operators_1 = operators_1_1;
            },
            function (lodash_1_1) {
                lodash_1 = lodash_1_1;
            },
            function (stratus_1_1) {
                stratus_1 = stratus_1_1;
            },
            function (environment_1_1) {
                environment_1 = environment_1_1;
            },
            function (backend_service_1_1) {
                backend_service_1 = backend_service_1_1;
            },
            function (model_1_1) {
                model_1 = model_1_1;
            },
            function (responsive_component_1_1) {
                responsive_component_1 = responsive_component_1_1;
            },
            function (icon_1_1) {
                icon_1 = icon_1_1;
            },
            function (platform_browser_1_1) {
                platform_browser_1 = platform_browser_1_1;
            }
        ],
        execute: function () {
            systemDir = '@stratusjs/angular';
            moduleName = 'link-dialog';
            parentModuleName = 'editor';
            min = !environment_1.cookie('env') ? '.min' : '';
            localDir = `${stratus_1.Stratus.BaseUrl}${boot.configuration.paths[`${systemDir}/*`].replace(/[^/]*$/, '').replace(/\/dist\/$/, '/src/')}`;
            LinkDialogComponent = class LinkDialogComponent extends responsive_component_1.ResponsiveComponent {
                constructor(dialogRef, data, fb, backend, snackBar, iconRegistry, sanitizer, ref) {
                    super();
                    this.dialogRef = dialogRef;
                    this.data = data;
                    this.fb = fb;
                    this.backend = backend;
                    this.snackBar = snackBar;
                    this.iconRegistry = iconRegistry;
                    this.sanitizer = sanitizer;
                    this.ref = ref;
                    this.title = moduleName + '_component';
                    this._ = lodash_1.default;
                    this.Stratus = stratus_1.Stratus;
                    this.apiBase = '/Api/Content';
                    this.contentEntities = [];
                    this.isContentLoading = true;
                    this.isSingleContentLoading = false;
                    this.limit = 20;
                    this.eventInsert = true;
                    this.isListView = false;
                    this.selected = [];
                    this.linkType = '';
                    this.linkText = '';
                    this.linkInitText = '';
                    this.linkURL = '';
                    this.linkTarget = false;
                    this.svgIcons = {};
                    this.isInitialized = false;
                    this.isDestroyed = false;
                    this.isStyled = false;
                }
                ngOnInit() {
                    this.uid = lodash_1.default.uniqueId(`sa_${lodash_1.default.snakeCase(moduleName)}_component_`);
                    stratus_1.Stratus.Instances[this.uid] = this;
                    stratus_1.Stratus.Internals.CssLoader(`${localDir}${parentModuleName}/${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({
                        selector_delete: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/delete.svg`,
                        selector_edit: `${stratus_1.Stratus.BaseUrl}sitetheorycore/images/icons/actionButtons/edit.svg`
                    }, (value, key) => this.iconRegistry.addSvgIcon(key, this.sanitizer.bypassSecurityTrustResourceUrl(value)).getNamedSvgIcon(key));
                    this.model = this.data.model;
                    this.property = this.data.property;
                    this.editor = this.data.editor;
                    this.eventManager = this.data.eventManager;
                    this.element = this.data.element;
                    if (lodash_1.default.isBoolean(this.data.eventInsert)) {
                        this.eventInsert = this.data.eventInsert;
                    }
                    this.dialogContentForm = this.fb.group({
                        contentSelectorInput: '',
                        linkTypeRadio: '',
                        linkTextInput: '',
                        linkURLInput: '',
                        linkTargetCheckbox: ''
                    });
                    this.dialogContentForm
                        .get('contentSelectorInput')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300), operators_1.tap(() => this.isContentLoading = true), operators_1.switchMap((value) => {
                        if (lodash_1.default.isUndefined(value)) {
                            return this.getQuery();
                        }
                        if (!lodash_1.default.isString(value)) {
                            this.content = value;
                            return this.getQuery();
                        }
                        return this.getQuery(value);
                    }))
                        .subscribe((response) => this.processContent(response));
                    this.backend
                        .get(this.getQueryUrl())
                        .pipe(operators_1.finalize(() => this.isContentLoading = false))
                        .subscribe((response) => this.processContent(response));
                    this.dialogContentForm
                        .get('linkTypeRadio')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300))
                        .subscribe((response) => this.linkType = response);
                    this.linkType = this.element && this.element.hasAttribute('data-content-id') ? 'content' : 'url';
                    this.dialogContentForm
                        .get('linkTypeRadio')
                        .patchValue(this.linkType);
                    this.dialogContentForm
                        .get('linkTextInput')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300))
                        .subscribe((response) => this.linkText = response);
                    this.linkInitText = this.linkText = this.element ? this.element.textContent : '';
                    this.dialogContentForm
                        .get('linkTextInput')
                        .patchValue(this.linkText);
                    this.dialogContentForm
                        .get('linkURLInput')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300))
                        .subscribe((response) => this.linkURL = response);
                    this.linkURL = this.element && this.element.hasAttribute('href') ? this.element.getAttribute('href') : '';
                    this.dialogContentForm
                        .get('linkURLInput')
                        .patchValue(this.linkURL);
                    this.dialogContentForm
                        .get('linkTargetCheckbox')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300))
                        .subscribe((response) => this.linkTarget = response);
                    this.linkTarget = this.element ? this.element.hasAttribute('target') : false;
                    this.dialogContentForm
                        .get('linkTargetCheckbox')
                        .patchValue(this.linkTarget);
                    if (this.element && this.element.hasAttribute('data-content-id')) {
                        this.isSingleContentLoading = true;
                        this.backend
                            .get(this.getQueryUrl(null, this.element.getAttribute('data-content-id')))
                            .pipe(operators_1.finalize(() => this.isSingleContentLoading = false))
                            .subscribe((response) => {
                            if (!response.ok || response.status !== 200 || lodash_1.default.isEmpty(response.body)) {
                                return null;
                            }
                            const payload = lodash_1.default.get(response.body, 'payload') || response.body;
                            if (lodash_1.default.isEmpty(payload) || Array.isArray(payload) || !lodash_1.default.isObject(payload)) {
                                return null;
                            }
                            this.contentEntity = payload;
                            this.isSingleContentLoading = false;
                            this.dialogContentForm
                                .get('contentSelectorInput')
                                .patchValue(this.contentEntity);
                            this.refresh();
                            return this.contentEntity;
                        });
                    }
                    this.isInitialized = true;
                }
                ngOnDestroy() {
                    this.isDestroyed = true;
                }
                refresh() {
                    if (this.isDestroyed) {
                        return new Promise(resolve => resolve());
                    }
                    return super.refresh();
                }
                onCancelClick() {
                    if (!this.eventManager) {
                        console.warn(`${moduleName}: event manager is not set.`);
                        return;
                    }
                    this.eventManager.trigger('restore', null, this.editor);
                    this.dialogRef.close();
                    this.refresh();
                }
                onPage(event) {
                    this.pageEvent = event;
                    this.getQuery(this.lastContentQuery).subscribe((response) => this.processContent(response));
                }
                getQueryUrl(query, id) {
                    query = (!lodash_1.default.isString(query) || lodash_1.default.isEmpty(query)) ? '' : `"${query}"`;
                    id = lodash_1.default.isEmpty(id) ? '' : `/${id}`;
                    return `${this.apiBase}${id}?limit=${this.limit}&options[isContent]=null&options[isCollection]=null&options[showRoutable]=true&options[showRouting]=true&q=${query}`;
                }
                getQuery(query) {
                    this.lastContentQuery = query;
                    this.isContentLoading = true;
                    return this.backend.get(this.getQueryUrl(query))
                        .pipe(operators_1.finalize(() => this.isContentLoading = false));
                }
                processContent(response) {
                    if (!response.ok || response.status !== 200 || lodash_1.default.isEmpty(response.body)) {
                        this.meta = {};
                        this.contentEntities = [];
                        this.refresh();
                        return this.contentEntities;
                    }
                    this.meta = lodash_1.default.get(response.body, 'meta') || {};
                    const payload = lodash_1.default.get(response.body, 'payload') || response.body;
                    if (lodash_1.default.isEmpty(payload) || !Array.isArray(payload)) {
                        this.contentEntities = [];
                        this.isContentLoading = false;
                        this.refresh();
                        return this.contentEntities;
                    }
                    this.contentEntities = payload;
                    this.isContentLoading = false;
                    this.refresh();
                    return this.contentEntities;
                }
                onAcceptClick() {
                    const link = this.linkType === 'content' ? this.createLink(this.content) : {
                        url: this.linkURL,
                        text: this.linkText,
                        target: this.linkTarget,
                    };
                    if (!link) {
                        const identifier = this.content && this.content.id ? `for Content ID: ${this.content.id}.` : 'without Content Selected or URL Input.';
                        console.warn(`${moduleName}: unable to build link ${identifier}`);
                        this.snackBar.open(`Unable to build link ${identifier}`, 'dismiss', {
                            duration: 5000,
                            horizontalPosition: 'right',
                            verticalPosition: 'bottom'
                        });
                        return;
                    }
                    if (this.content && this.content.id) {
                        this.selected.push(this.content.id);
                    }
                    if (!this.eventInsert) {
                        if (!(this.model instanceof model_1.Model)) {
                            console.warn(`${moduleName}: event manager not available.`);
                            return;
                        }
                        if (!lodash_1.default.isString(this.property)) {
                            console.warn(`${moduleName}: event manager not available.`);
                            return;
                        }
                        console.warn(`${moduleName}: disabling eventInsert is not recommended.`);
                        this.model.set(this.property, this.model.get(this.property) + link);
                        return;
                    }
                    if (!this.eventManager) {
                        console.warn(`${moduleName}: event manager is not set.`);
                        return;
                    }
                    this.eventManager.trigger('insert', link, this.editor);
                    this.onCancelClick();
                }
                isSelected(content) {
                    if (lodash_1.default.isUndefined(content)) {
                        return;
                    }
                    return lodash_1.default.includes(this.selected, content.id);
                }
                createLink(content) {
                    if (!content) {
                        console.warn(`${moduleName}: unable to create link for empty content`);
                        return null;
                    }
                    if (!content.id) {
                        console.warn(`${moduleName}: unable to find content id for content:`, content);
                        return null;
                    }
                    if (!content.contentType || !content.contentType.name) {
                        console.warn(`${moduleName}: unable to find content type for content id: ${content.id}`);
                        return null;
                    }
                    if (!content.routing || !content.routing.length || !content.routing[0]) {
                        console.warn(`${moduleName}: unable to find routing for ${content.contentType.name} id: ${content.id}`);
                        return null;
                    }
                    if (!content.routing[0].url) {
                        console.warn(`${moduleName}: unable to find url for ${content.contentType.name} id: ${content.id}`);
                        return null;
                    }
                    if (!content.version) {
                        console.warn(`${moduleName}: unable to find content version for ${content.contentType.name} id: ${content.id}`);
                        return null;
                    }
                    if (!content.version.title || !content.version.title.length) {
                        console.warn(`${moduleName}: unable to find title for ${content.contentType.name} id: ${content.id}`);
                        return null;
                    }
                    return {
                        url: `/${content.routing[0].url}`,
                        title: content.version.title,
                        text: this.linkText,
                        target: this.linkTarget,
                        id: content.id
                    };
                }
                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;
                }
                displayContentText(content) {
                    if (!content) {
                        return;
                    }
                    const routing = lodash_1.default.get(content, 'routing[0].url');
                    const routingText = !lodash_1.default.isUndefined(routing) ? ` (/${routing})` : ' (No route!)';
                    const contentId = lodash_1.default.get(content, 'id');
                    const contentIdText = !lodash_1.default.isUndefined(contentId) ? `Content: ${contentId}` : null;
                    return (lodash_1.default.get(content, 'version.title') || contentIdText) + routingText;
                }
                goToUrl(content) {
                    if (!content || !content.contentType) {
                        console.error('unable to execute goToUrl() because a valid model content was not provided.');
                        return;
                    }
                    window.open(content.contentType.editUrl + '?id=' + content.id, '_blank');
                }
            };
            LinkDialogComponent = __decorate([
                core_1.Component({
                    selector: `sa-${moduleName}`,
                    templateUrl: `${localDir}/${parentModuleName}/${moduleName}.component${min}.html`,
                }),
                __param(1, core_1.Inject(dialog_1.MAT_DIALOG_DATA)),
                __metadata("design:paramtypes", [dialog_1.MatDialogRef, Object, forms_1.FormBuilder,
                    backend_service_1.BackendService,
                    snack_bar_1.MatSnackBar,
                    icon_1.MatIconRegistry,
                    platform_browser_1.DomSanitizer,
                    core_1.ChangeDetectorRef])
            ], LinkDialogComponent);
            exports_1("LinkDialogComponent", LinkDialogComponent);
        }
    };
});

//# sourceMappingURL=link-dialog.component.js.map
