import { Host, h } from "@stencil/core";
import { Lang } from "../../services/lang";
import { getMeta, tinyMDtoHTML } from "../../utils/helpers";
import axios from "axios";
const GALLERY_ROUTE = '/services/media';
export class XGallery {
    constructor() {
        this.appendHeaders = {};
        this.endpoint = '';
        this.loading = false;
        this.errorMessage = undefined;
        this.selectedMedia = undefined;
        this.galleryCollection = [];
        this.galleryPage = 1;
        this.galleryResultsCount = 0;
        this.galleryHasMore = false;
        this.galleryUploadProgress = undefined;
        this.generatedCollection = [];
    }
    /**
     * Call the gallery window
     */
    async load(cropperOptions) {
        this.resetData();
        this.loadGalleryAssets();
        this.loadGeneratedAssets();
        cropperOptions && this.inputImage.setCropperOptions(cropperOptions);
        this.modal.open();
    }
    /**
     * Add initial values to components
     */
    resetData() {
        this.loading = false;
        this.errorMessage = null;
        this.galleryCollection = [];
        this.galleryPage = 1;
        this.galleryResultsCount = 0;
        this.galleryHasMore = false;
        this.generatedCollection = [];
        this.selectedMedia = null;
    }
    /**
     * Axios response error capture
     */
    catchRequestFail(err) {
        if (err.response) {
            let data = err.response.data;
            return data.message ? data.message : `Response ${err.response.status}`;
        }
        else if (err.request) {
            return err.request;
        }
        else {
            return err.message;
        }
    }
    /**
     * Get element by UUID
     */
    getIndexCollectionByUUID(collection, uuid) {
        return collection.findIndex(x => x.uuid === uuid);
    }
    /**
     * Loading all images saved for actual user
     */
    loadGalleryAssets(page = 1) {
        this.errorMessage = null;
        this.loading = true;
        axios({
            method: 'GET',
            url: `${this.endpoint}${GALLERY_ROUTE}/gallery?page=${page}`,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'X-CSRF-TOKEN': getMeta('csrf-token') })
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            this.galleryPage = page;
            if (page > 1) {
                this.galleryCollection = this.galleryCollection.concat(data.items);
            }
            else {
                this.galleryCollection = data.items;
            }
            this.galleryHasMore = data.has_more;
            this.galleryResultsCount = data.total;
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * Loading last generated images for actual user
     */
    loadGeneratedAssets() {
        this.errorMessage = null;
        this.loading = true;
        axios({
            method: 'GET',
            url: `${this.endpoint}${GALLERY_ROUTE}/generate`,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'X-CSRF-TOKEN': getMeta('csrf-token') })
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            this.generatedCollection = data.items;
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * Select the element ready for choose
     */
    onSelectMedia(media) {
        this.selectedMedia = media;
    }
    /**
     * Upload image and return file
     */
    onUploadImage(e) {
        if (this.loading) {
            return;
        }
        this.galleryCollection.unshift({
            uuid: 'upload-image',
            url: URL.createObjectURL(e.detail),
            type: 'image',
            loading: true,
        });
        this.errorMessage = null;
        this.galleryUploadProgress = null;
        this.loading = true;
        const data = new FormData();
        data.append('image', e.detail);
        axios({
            method: 'POST',
            url: `${this.endpoint}${GALLERY_ROUTE}/gallery`,
            data: data,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'X-CSRF-TOKEN': getMeta('csrf-token') }),
            onUploadProgress: progressEvent => {
                this.galleryUploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            }
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            const index = this.getIndexCollectionByUUID(this.galleryCollection, 'upload-image');
            this.galleryCollection[index] = data;
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
            this.galleryUploadProgress = null;
        });
    }
    /**
     * Delete image and return confirmation
     */
    onDeleteImage(uuid) {
        this.errorMessage = null;
        this.loading = true;
        axios({
            method: 'DELETE',
            url: `${this.endpoint}${GALLERY_ROUTE}/gallery?uuid=${uuid}`,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'X-CSRF-TOKEN': getMeta('csrf-token') })
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            const index = this.getIndexCollectionByUUID(this.galleryCollection, data.uuid);
            if (index != -1) {
                this.galleryCollection.splice(index, 1);
                this.selectedMedia = null;
            }
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * Send IA prompt and return image result
     */
    onPromptImage(prompt) {
        if (this.loading) {
            return;
        }
        this.generatedCollection.unshift({
            uuid: 'generate-image',
            url: '',
            type: 'image',
            loading: true,
        });
        this.errorMessage = null;
        this.loading = true;
        this.promptInput.setAttribute('disabled', 'disabled');
        const data = new FormData();
        data.append('prompt', prompt);
        axios({
            method: 'POST',
            url: `${this.endpoint}${GALLERY_ROUTE}/generate`,
            data: data,
            headers: Object.assign(Object.assign({}, this.appendHeaders), { 'X-CSRF-TOKEN': getMeta('csrf-token') })
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            const index = this.getIndexCollectionByUUID(this.generatedCollection, 'generate-image');
            this.generatedCollection[index] = data;
        })
            .catch(err => {
            this.generatedCollection.shift();
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
            this.promptInput.removeAttribute('disabled');
        });
    }
    /**
     * On window finish selection of media element
     */
    onFinishSelectMedia(media) {
        this.modal.close();
        setTimeout(() => {
            this.resetData();
        }, 500);
        media ? this.onSelected.emit(media) : this.onCanceled.emit();
    }
    /**
     * Render the component
     */
    render() {
        var _a;
        return (h(Host, { key: '6ec66ce340c0418e53ac0e55d95620bda3e14324' }, h("x-modal", { key: '1b37ce8172531043b6945c03b9c3f0ee5718bde6', class: "image-gallery-modal", ref: el => (this.modal = el), closable: false, size: "big" }, h("x-card", { key: 'ecc9f511b593df1de10580d89fe167ea84c35620', icon: "image-gallery", "icon-color": "primary", class: "gallery-picker" }, h("x-tabs", { key: '632d04045d2cac40751673a710a5a581ff1f4b5e' }, h("x-tab", { key: 'fa1de15f462f78972c294b9d70e8f68de9d27224', label: Lang.get('gallery.gallery'), badge: ((_a = this.selectedMedia) === null || _a === void 0 ? void 0 : _a.type) == 'image' ? 1 : null }, h("div", { key: '4a8595061b568f62d46bc94235874aa16547c6b8', class: "items" }, h("x-input-image", { key: '337f55f8a9b71c8a8ced67f3dc872cd97d199b92', ref: el => this.inputImage = el, "without-preview": true, onFile: e => this.onUploadImage(e) }, h("x-cropper", { key: '96e89a5e830c40fedbcc72c3cdc212b787e45695' })), this.galleryCollection.map(item => {
            var _a;
            return (h("x-gallery-image", { url: item.url, key: item.uuid, uuid: item.uuid, selected: ((_a = this.selectedMedia) === null || _a === void 0 ? void 0 : _a.uuid) == item.uuid, loading: item.loading, onClick: () => this.onSelectMedia(item) }, h("a", { href: item.url, download: true, title: Lang.get('gallery.download') }, h("x-icon", { name: "download" })), h("button", { onClick: () => this.onDeleteImage(item.uuid), title: Lang.get('gallery.delete') }, h("x-icon", { name: "trash" }))));
        })), this.galleryHasMore && !this.loading && (h("x-divider", { key: '21909e237bf65bd5a6625705dbdb67e64a0a783c', align: "center" }, h("a", { key: 'c7bfd5fe9be1d3599517399fd1b7b2a5fb4af3d0', href: "#", class: { disabled: this.loading }, onClick: () => this.loadGalleryAssets(this.galleryPage + 1) }, Lang.get('gallery.view-more')))), !!this.galleryResultsCount && !this.loading && (h("div", { key: '52fbb2db3279696db733c549d90895152e4a0fb5', class: "results mt-4", innerHTML: tinyMDtoHTML(Lang.get('gallery.gallery-results', {
                length: this.galleryCollection.length,
                total: this.galleryResultsCount,
            })) })), this.errorMessage && (h("x-alert", { key: '0777155f30afbeb2f58e12bfdab147a53725eda9', small: true, color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: '8269654f0ecd331f931437285d9e52e3bac03fcc', loading: !this.galleryUploadProgress, value: this.galleryUploadProgress })), h("x-tab", { key: '7247ba853b2ad6adb787e2b35a3fd6f781a92a4b', label: Lang.get('gallery.generate') }, h("x-input", { key: '32ac3f3de670075e34763e8b7535743992110e75', ref: el => (this.promptInput = el), placeholder: Lang.get('gallery.generate-placeholder') }, h("x-icon", { key: '8cd94693e2a39dfffdae1a796f50b57be136d72e', name: "chatgpt", size: "24px", slot: "indicator" }), h("x-button", { key: '7805d0818f5b434e31a22918ce20710275f3f9cb', icon: "right", slot: "buttons", onClick: () => this.onPromptImage(String(this.promptInput.value)) })), this.generatedCollection.length > 0 && h("x-divider", { key: '34838f7753b804210a00a4c850172a15b522648d', class: "my-4" }, Lang.get('gallery.generated-images')), this.generatedCollection.length > 0 && (h("div", { key: 'b3966cf2ec6d690e2995ca3e5739ad143785808c', class: "items" }, this.generatedCollection.map(item => {
            var _a;
            return (h("x-gallery-image", { url: item.url, key: item.uuid, uuid: item.uuid, selected: ((_a = this.selectedMedia) === null || _a === void 0 ? void 0 : _a.uuid) == item.uuid, loading: item.loading, onClick: () => this.onSelectMedia(item) }, h("a", { href: item.url, download: true, target: "_blank", title: Lang.get('gallery.download') }, h("x-icon", { name: "download" })), h("button", { onClick: () => this.onPromptImage(item.prompt), title: Lang.get('gallery.reprompt', { prompt: item.prompt }) }, h("x-icon", { name: "sparkling" }))));
        }))), this.errorMessage && (h("x-alert", { key: 'c57b02deb8e9d5f565938bd9aed1bc04928cc3d0', small: true, class: "mt-3", color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: 'af8520f0f9c6b893b9c4ee9833c6b18819e6f793', loading: true }))), h("x-card-segment", { key: '0a9e492af57a70a754042b4edb6acee4389366d9', slot: "footer", tinted: true }, h("x-button", { key: 'd5254b66c68685123ec6fe99eabffe8b01908941', small: true, icon: "left", onClick: () => this.onFinishSelectMedia() }, Lang.get('gallery.back')), h("x-button", { key: 'd42d3cd9f188102230d694e062aed4c83ad77ad4', small: true, icon: "check", color: "primary", disabled: !this.selectedMedia, onClick: () => this.onFinishSelectMedia(this.selectedMedia) }, Lang.get('gallery.select')))))));
    }
    static get is() { return "x-gallery"; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "appendHeaders": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "{[key: string]: string}",
                    "resolved": "{ [key: string]: string; }",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element append headers"
                },
                "defaultValue": "{}"
            },
            "endpoint": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Server-side proccesing route"
                },
                "attribute": "endpoint",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "errorMessage": {},
            "selectedMedia": {},
            "galleryCollection": {},
            "galleryPage": {},
            "galleryResultsCount": {},
            "galleryHasMore": {},
            "galleryUploadProgress": {},
            "generatedCollection": {}
        };
    }
    static get events() {
        return [{
                "method": "onSelected",
                "name": "selected",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On finish selected media event"
                },
                "complexType": {
                    "original": "MediaElement",
                    "resolved": "{ uuid: string; url: string; type?: string; loading?: boolean; prompt?: string; }",
                    "references": {
                        "MediaElement": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-gallery/component.tsx",
                            "id": "src/components/x-gallery/component.tsx::MediaElement"
                        }
                    }
                }
            }, {
                "method": "onCanceled",
                "name": "canceled",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On cancel event"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "load": {
                "complexType": {
                    "signature": "(cropperOptions?: CropperOptions) => Promise<void>",
                    "parameters": [{
                            "name": "cropperOptions",
                            "type": "{ source: string | File; sizes?: CropperSizeOption[]; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "CropperOptions": {
                            "location": "import",
                            "path": "../x-cropper/component",
                            "id": "src/components/x-cropper/component.tsx::CropperOptions"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Call the gallery window",
                    "tags": []
                }
            }
        };
    }
}
