System.register(["@angular/core", "@angular/forms", "@angular/material/dialog", "@angular/material/snack-bar", "rxjs/operators", "lodash", "@stratusjs/runtime/stratus", "@stratusjs/core/environment", "../backend.service", "@stratusjs/angularjs/services/model", "../core/responsive.component"], 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, operators_1, lodash_1, stratus_1, environment_1, backend_service_1, model_1, responsive_component_1, systemDir, moduleName, parentModuleName, min, localDir, MediaDialogComponent;
    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 (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;
            }
        ],
        execute: function () {
            systemDir = '@stratusjs/angular';
            moduleName = 'media-dialog';
            parentModuleName = 'editor';
            min = !environment_1.cookie('env') ? '.min' : '';
            localDir = `${stratus_1.Stratus.BaseUrl}${boot.configuration.paths[`${systemDir}/*`].replace(/[^/]*$/, '').replace(/\/dist\/$/, '/src/')}`;
            MediaDialogComponent = class MediaDialogComponent extends responsive_component_1.ResponsiveComponent {
                constructor(dialogRef, data, fb, backend, snackBar, ref) {
                    super();
                    this.dialogRef = dialogRef;
                    this.data = data;
                    this.fb = fb;
                    this.backend = backend;
                    this.snackBar = snackBar;
                    this.ref = ref;
                    this.title = moduleName + '_component';
                    this._ = lodash_1.default;
                    this.Stratus = stratus_1.Stratus;
                    this.apiBase = '/Api/Media';
                    this.mediaEntities = [];
                    this.isMediaLoading = true;
                    this.limit = 20;
                    this.eventInsert = true;
                    this.selected = [];
                    this.embedly = true;
                }
                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`);
                    this.model = this.data.model;
                    this.property = this.data.property;
                    this.editor = this.data.editor;
                    this.eventManager = this.data.eventManager;
                    if (lodash_1.default.isBoolean(this.data.eventInsert)) {
                        this.eventInsert = this.data.eventInsert;
                    }
                    this.dialogMediaForm = this.fb.group({
                        mediaQueryInput: ''
                    });
                    this.dialogMediaForm
                        .get('mediaQueryInput')
                        .valueChanges
                        .pipe(operators_1.debounceTime(300), operators_1.tap(() => {
                    }), operators_1.switchMap((value) => {
                        return this.getQuery(value);
                    }))
                        .subscribe((response) => this.processMedia(response));
                    this.getQuery().subscribe((response) => this.processMedia(response));
                    this.refresh();
                }
                onCancelClick() {
                    this.dialogRef.close();
                    this.refresh();
                }
                onPage(event) {
                    this.pageEvent = event;
                    this.getQuery(this.lastMediaQuery).subscribe((response) => this.processMedia(response));
                }
                getQueryUrl(query) {
                    let limit = this.limit;
                    let paging = 1;
                    if (this.pageEvent) {
                        limit = this.pageEvent.pageSize;
                        paging = this.pageEvent.pageIndex + 1;
                    }
                    query = (lodash_1.default.isString(query) && !lodash_1.default.isEmpty(query)) ? `"${query}"` : '';
                    return `${this.apiBase}?limit=${limit}&p=${paging}&q=${query}`;
                }
                getQuery(query) {
                    this.lastMediaQuery = query;
                    this.isMediaLoading = true;
                    return this.backend.get(this.getQueryUrl(query))
                        .pipe(operators_1.finalize(() => this.isMediaLoading = false));
                }
                processMedia(response) {
                    if (!response.ok || response.status !== 200 || lodash_1.default.isEmpty(response.body)) {
                        this.meta = {};
                        this.mediaEntities = [];
                        this.refresh();
                        return this.mediaEntities;
                    }
                    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.mediaEntities = [];
                        this.isMediaLoading = false;
                        this.refresh();
                        return this.mediaEntities;
                    }
                    this.mediaEntities = payload;
                    this.isMediaLoading = false;
                    this.refresh();
                    return this.mediaEntities;
                }
                select(media) {
                    if (lodash_1.default.isUndefined(media)) {
                        return;
                    }
                    const mediaElement = this.createEmbed(media);
                    if (!mediaElement) {
                        console.warn(`media-dialog: unable to build embed for Media ID: ${media.id}`);
                        this.snackBar.open(`Unable to build embed for Media ID: ${media.id}.`, 'dismiss', {
                            duration: 5000,
                            horizontalPosition: 'right',
                            verticalPosition: 'bottom'
                        });
                        return;
                    }
                    this.selected.push(media.id);
                    if (!this.eventInsert) {
                        if (!(this.model instanceof model_1.Model)) {
                            console.warn('media-dialog: event manager not available.');
                            return;
                        }
                        if (!lodash_1.default.isString(this.property)) {
                            console.warn('media-dialog: event manager not available.');
                            return;
                        }
                        console.warn('media-dialog: disabling eventInsert is not recommended.');
                        this.model.set(this.property, this.model.get(this.property) + mediaElement);
                        return;
                    }
                    if (!this.eventManager) {
                        console.warn('media-dialog: event manager is not set.');
                        return;
                    }
                    this.eventManager.trigger('insert', mediaElement, this.editor);
                }
                isSelected(media) {
                    if (lodash_1.default.isUndefined(media)) {
                        return;
                    }
                    return lodash_1.default.includes(this.selected, media.id);
                }
                createEmbed(media) {
                    if (media._embedCode) {
                        return {
                            html: media._embedCode
                        };
                    }
                    if (lodash_1.default.startsWith(media.mime, 'image')) {
                        if (!media._thumbnailUrl || (media.service === 'directLink' && !media.file)) {
                            console.warn(`media-dialog: unable to determine image source for media id: ${media.id}`);
                            return null;
                        }
                        return {
                            html: `<img src="${media._thumbnailUrl || media.file}" alt="${media.name || media.filename}" ${media.mime !== 'image/gif' ? 'data-stratus-src' : ''}>`
                        };
                    }
                    if (media.mime === 'video') {
                        if (media.embed) {
                            return {
                                html: media.embed
                            };
                        }
                        const iframeAttributes = 'width="100%" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true" webkitAllowFullScreen="" mozAllowFullScreen=""';
                        if (media.service === 'facebook') {
                            const mediaUrl = media.url || media.file;
                            if (!mediaUrl) {
                                console.warn(`media-dialog: unable to find url for video with media id: ${media.id}`);
                                return null;
                            }
                            if (this.embedly) {
                                return {
                                    html: `<div class="fr-embedly"
                                 data-original-embed="<a href='${mediaUrl}' data-card-branding='0' class='embedly-card'></a>"
                                 style="height: 998px;">
                                 <a href="${mediaUrl}" data-card-branding="0" class="embedly-card"></a>
                             </div>`
                                };
                            }
                            return {
                                html: `<iframe src="https://www.facebook.com/plugins/video.php?href=${mediaUrl}" ${iframeAttributes}></iframe>`
                            };
                        }
                        if (!media.serviceMediaId) {
                            console.warn(`media-dialog: unable to find serviceMediaId for video with media id: ${media.id}`);
                            return null;
                        }
                        if (media.service === 'vimeo') {
                            if (this.embedly) {
                                return {
                                    html: `<div class="fr-embedly"
                                data-original-embed="<a href='https://vimeo.com/${media.serviceMediaId}' data-card-branding='0' class='embedly-card'></a>"
                                style="height: 370px;">
                                <a href="https://vimeo.com/${media.serviceMediaId}" data-card-branding="0" class="embedly-card"></a>
                            </div>`
                                };
                            }
                            return {
                                html: `<iframe src="https://player.vimeo.com/video/${media.serviceMediaId}" ${iframeAttributes}></iframe>`
                            };
                        }
                        if (media.service === 'youtube') {
                            if (this.embedly) {
                                return {
                                    html: `<div class="fr-embedly"
                                 data-original-embed="<a href='https://www.youtube.com/watch?v=${media.serviceMediaId}' data-card-branding='0' class='embedly-card'></a>"
                                 style="height: 370px;">
                                <a href="https://www.youtube.com/watch?v=${media.serviceMediaId}" data-card-branding="0" class="embedly-card"></a>
                            </div>`
                                };
                            }
                            return {
                                html: `<iframe src="https://www.youtube.com/embed/${media.serviceMediaId}" ${iframeAttributes}></iframe>`
                            };
                        }
                        console.warn(`media-dialog: unsupported service: ${media.service} for media id: ${media.id}`);
                        return null;
                    }
                    if (lodash_1.default.startsWith(media.mime, 'audio')) {
                        if (!media.url) {
                            console.warn(`media-dialog: unable to determine audio source for media id: ${media.id}`);
                            return null;
                        }
                        return {
                            html: `<audio controls>
                        <source src="https://${media.url}" type="${media.mime}">
                        <p>
                            Your browser doesn't support HTML5 audio, but you can <a href="https://${media.url}">download the audio here</a>.
                        </p>
                    </audio>`
                        };
                    }
                    if (media.mime === 'application/pdf') {
                        if (!media.url) {
                            console.warn(`media-dialog: unable to determine PDF source for media id: ${media.id}`);
                            return null;
                        }
                        if (this.embedly) {
                            return {
                                html: `<div class="fr-embedly"
                             data-original-embed="<a href='https://${media.url}' data-card-branding='0' class='embedly-card'></a>"
                             style="height: 71px;">
                             <a href="https://${media.url}" data-card-branding="0" class="embedly-card"></a>
                         </div>`
                            };
                        }
                        return {
                            html: `<iframe src="https://docs.google.com/viewer?url=${media.url}&embedded=true" style="min-height: 500px;" width="100%"></iframe>`
                        };
                    }
                    if (media.mime === 'application/msword') {
                        if (!media.url) {
                            console.warn(`media-dialog: unable to determine Word Document source for media id: ${media.id}`);
                            return null;
                        }
                        if (this.embedly) {
                            return {
                                html: `<div class="fr-embedly"
                             data-original-embed="<a href='https://${media.url}' data-card-branding='0' class='embedly-card'></a>"
                             style="height: 71px;">
                             <a href="https://${media.url}" data-card-branding="0" class="embedly-card"></a>
                         </div>`
                            };
                        }
                        return {
                            html: `<iframe src="https://docs.google.com/viewer?url=${media.url}&embedded=true" style="min-height: 500px;" width="100%"></iframe>`
                        };
                    }
                    console.warn(`media-dialog: unsupported mime type: ${media.mime} for media id: ${media.id}`);
                    return null;
                }
            };
            MediaDialogComponent = __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,
                    core_1.ChangeDetectorRef])
            ], MediaDialogComponent);
            exports_1("MediaDialogComponent", MediaDialogComponent);
        }
    };
});

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