import * as i0 from '@angular/core';
import { Injectable, forwardRef, Input, Component } from '@angular/core';
import * as i1 from 'ngx-bootstrap/modal';
import * as i5 from 'ngx-bootstrap/tooltip';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import * as i2 from '@c8y/ngx-components/static-assets/data';
import * as i3 from '@c8y/ngx-components';
import { CoreModule } from '@c8y/ngx-components';
import * as i4 from '@angular/common';

class StaticAssetsModalService {
    constructor(modal) {
        this.modal = modal;
    }
    async pickStaticAsset(options) {
        const component = await import('@c8y/ngx-components/static-assets/modal').then(m => m.StaticAssetsModalComponent);
        const initialState = options || {};
        const modalRef = this.modal.show(component, {
            class: 'modal-lg',
            ariaDescribedby: 'modal-body',
            ariaLabelledBy: 'modal-title',
            ignoreBackdropClick: true,
            initialState,
            keyboard: false
        });
        return modalRef.content.result;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: StaticAssetsModalService, deps: [{ token: i1.BsModalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: StaticAssetsModalService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: StaticAssetsModalService, decorators: [{
            type: Injectable,
            args: [{ providedIn: 'root' }]
        }], ctorParameters: () => [{ type: i1.BsModalService }] });

class StaticAssetsFilePickerComponent {
    constructor(staticAssetsModal, staticAssets) {
        this.staticAssetsModal = staticAssetsModal;
        this.staticAssets = staticAssets;
        this.isCSSURL = false;
        this.staticAssetType = 'branding';
        this.supportedFileExtensions = [];
        this.layout = 'grid';
        this.size = 48;
        this.loading = false;
        this.currentFile = undefined;
    }
    writeValue(value) {
        if (/^url\('.*'\)$/.test(value)) {
            value = value.replace(/^url\('/, '').replace(/'\)$/, '');
        }
        if (/^url\(.*\)$/.test(value)) {
            value = value.replace(/^url\(/, '').replace(/\)$/, '');
        }
        this.currentValue = value;
        this.loadFileDetails(value);
    }
    registerOnChange(fn) {
        this.onChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    async loadFileDetails(currentUrl) {
        if (!currentUrl) {
            this.currentFile = undefined;
            return;
        }
        this.loading = true;
        try {
            const fileList = await this.staticAssets.listFilesCached(this.staticAssetType);
            const foundFile = fileList.find(file => currentUrl.includes(file.path));
            this.currentFile = foundFile;
            if (!foundFile) {
                const filePresent = await this.ensureFileExists(currentUrl);
                if (filePresent) {
                    this.currentFile = {
                        path: currentUrl,
                        fileName: currentUrl.split('/').pop(),
                        originalFileName: currentUrl.split('/').pop()
                    };
                }
            }
        }
        catch (e) { }
        this.loading = false;
    }
    clear() {
        this.onChange('');
        this.currentFile = undefined;
        this.currentValue = '';
        this.onTouched();
    }
    async openFilePicker() {
        try {
            const res = await this.staticAssetsModal.pickStaticAsset({
                layout: this.layout,
                assetType: this.staticAssetType,
                supportedFileExtensions: this.supportedFileExtensions
            });
            const value = this.isCSSURL ? `url(${res.path})` : res.path;
            this.onChange(value);
            this.currentFile = res;
            this.currentValue = value;
            this.onTouched();
        }
        catch (e) {
            // modal closed
        }
    }
    async ensureFileExists(url) {
        const response = await fetch(url);
        return response.status === 200;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: StaticAssetsFilePickerComponent, deps: [{ token: StaticAssetsModalService }, { token: i2.StaticAssetsService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: StaticAssetsFilePickerComponent, isStandalone: true, selector: "c8y-static-assets-file-picker", inputs: { isCSSURL: "isCSSURL", staticAssetType: "staticAssetType", supportedFileExtensions: "supportedFileExtensions", layout: "layout", size: "size" }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => StaticAssetsFilePickerComponent),
                multi: true
            }
        ], ngImport: i0, template: "\n<div class=\"d-flex a-i-center gap-8\">\n  <div *ngIf=\"!currentValue else fileSelected\" class=\"d-contents\">\n    <i c8yIcon=\"no-image\" class=\"icon-48 text-muted\"></i>\n    <p class=\"m-r-auto text-muted\"><em translate>No file selected.</em></p>\n  </div>\n\n  <ng-template #fileSelected>\n    <c8y-loading *ngIf=\"loading\"></c8y-loading>\n    <div *ngIf=\"!loading && !currentFile\">\n      <p translate>Unable to locate file: \"{{ currentValue }}\"</p>\n    </div>\n\n    <div *ngIf=\"!loading && currentFile\" style=\"min-height: 48px\" class=\"d-flex a-i-center\">\n      <img *ngIf=\"currentFile\" [src]=\"currentFile.path\" class=\"img-responsive\" [ngStyle]=\"{'width.px': size}\" alt=\"{{currentFile?.fileName }}\">\n    </div>\n    <span class=\"text-truncate\" title=\"{{ currentFile?.fileName || currentValue }}\">{{ currentFile?.fileName || currentValue }}</span>\n    <button class=\" m-l-auto btn btn-dot btn-dot--danger\"\n      type=\"button\" (click)=\"clear()\"\n      [delay]=\"500\"\n      [attr.aria-label]=\"'Remove' | translate\"\n      placement=\"top\"\n      tooltip=\"{{'Remove' | translate}}\">\n      <i c8yIcon=\"minus-circle\"></i>\n    </button>\n  </ng-template>\n\n  <button (click)=\"openFilePicker()\" class=\"btn btn-default btn-sm\">\n    <span *ngIf=\"!currentFile\">\n      {{'Select' | translate}}\n    </span>\n    <span *ngIf=\"currentFile\">\n      {{'Replace' | translate}}\n    </span>\n  </button>\n</div>\n\n", dependencies: [{ kind: "ngmodule", type: CoreModule }, { kind: "directive", type: i3.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i3.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i4.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "component", type: i3.LoadingComponent, selector: "c8y-loading", inputs: ["layout", "progress", "message"] }, { kind: "ngmodule", type: TooltipModule }, { kind: "directive", type: i5.TooltipDirective, selector: "[tooltip], [tooltipHtml]", inputs: ["adaptivePosition", "tooltip", "placement", "triggers", "container", "containerClass", "boundariesElement", "isOpen", "isDisabled", "delay", "tooltipHtml", "tooltipPlacement", "tooltipIsOpen", "tooltipEnable", "tooltipAppendToBody", "tooltipAnimation", "tooltipClass", "tooltipContext", "tooltipPopupDelay", "tooltipFadeDuration", "tooltipTrigger"], outputs: ["tooltipChange", "onShown", "onHidden", "tooltipStateChanged"], exportAs: ["bs-tooltip"] }, { kind: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: StaticAssetsFilePickerComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-static-assets-file-picker', standalone: true, imports: [CoreModule, TooltipModule], providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => StaticAssetsFilePickerComponent),
                            multi: true
                        }
                    ], template: "\n<div class=\"d-flex a-i-center gap-8\">\n  <div *ngIf=\"!currentValue else fileSelected\" class=\"d-contents\">\n    <i c8yIcon=\"no-image\" class=\"icon-48 text-muted\"></i>\n    <p class=\"m-r-auto text-muted\"><em translate>No file selected.</em></p>\n  </div>\n\n  <ng-template #fileSelected>\n    <c8y-loading *ngIf=\"loading\"></c8y-loading>\n    <div *ngIf=\"!loading && !currentFile\">\n      <p translate>Unable to locate file: \"{{ currentValue }}\"</p>\n    </div>\n\n    <div *ngIf=\"!loading && currentFile\" style=\"min-height: 48px\" class=\"d-flex a-i-center\">\n      <img *ngIf=\"currentFile\" [src]=\"currentFile.path\" class=\"img-responsive\" [ngStyle]=\"{'width.px': size}\" alt=\"{{currentFile?.fileName }}\">\n    </div>\n    <span class=\"text-truncate\" title=\"{{ currentFile?.fileName || currentValue }}\">{{ currentFile?.fileName || currentValue }}</span>\n    <button class=\" m-l-auto btn btn-dot btn-dot--danger\"\n      type=\"button\" (click)=\"clear()\"\n      [delay]=\"500\"\n      [attr.aria-label]=\"'Remove' | translate\"\n      placement=\"top\"\n      tooltip=\"{{'Remove' | translate}}\">\n      <i c8yIcon=\"minus-circle\"></i>\n    </button>\n  </ng-template>\n\n  <button (click)=\"openFilePicker()\" class=\"btn btn-default btn-sm\">\n    <span *ngIf=\"!currentFile\">\n      {{'Select' | translate}}\n    </span>\n    <span *ngIf=\"currentFile\">\n      {{'Replace' | translate}}\n    </span>\n  </button>\n</div>\n\n" }]
        }], ctorParameters: () => [{ type: StaticAssetsModalService }, { type: i2.StaticAssetsService }], propDecorators: { isCSSURL: [{
                type: Input
            }], staticAssetType: [{
                type: Input
            }], supportedFileExtensions: [{
                type: Input
            }], layout: [{
                type: Input
            }], size: [{
                type: Input
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { StaticAssetsFilePickerComponent, StaticAssetsModalService };
//# sourceMappingURL=c8y-ngx-components-static-assets.mjs.map
