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: '4034131b240e93ad7dd41bd307a3ceac6bb160c0' }, h("x-modal", { key: '173c10aa8dbaa8318bebea6d2324482134016fa4', class: "image-gallery-modal", ref: el => (this.modal = el), closable: false, size: "big" }, h("x-card", { key: '5aa146c11695465daedb18dfa46f74bca2fb26e7', icon: "image-gallery", "icon-color": "primary", class: "gallery-picker" }, h("x-tabs", { key: '1990449643300d31b092af80bb9bc8182cbbd325' }, h("x-tab", { key: '023effe494279f0bbc4de22b4473854590f43c27', label: Lang.get('gallery.gallery'), badge: ((_a = this.selectedMedia) === null || _a === void 0 ? void 0 : _a.type) == 'image' ? 1 : null }, h("div", { key: '63e3a10ba7338222c9ba23738b6e06d1f97d51c0', class: "items" }, h("x-input-image", { key: '67c9053876c405116cf64435da4eea04061ce4a4', ref: el => this.inputImage = el, "without-preview": true, onFile: e => this.onUploadImage(e) }, h("x-cropper", { key: '46baaa4957a0db95018bc36e99bbac1d8e8371d7' })), 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: 'a2ae205a07c73b31527dc747bfe19ee4cf1b1166', align: "center" }, h("a", { key: '6a6a9deb4adf4fbde677e580bd318fa0a1e15716', href: "#", class: { disabled: this.loading }, onClick: () => this.loadGalleryAssets(this.galleryPage + 1) }, Lang.get('gallery.view-more')))), !!this.galleryResultsCount && !this.loading && (h("div", { key: 'e80ffca6eac64aef143a2e959fea986eff9855c7', class: "results mt-4", innerHTML: tinyMDtoHTML(Lang.get('gallery.gallery-results', {
                length: this.galleryCollection.length,
                total: this.galleryResultsCount,
            })) })), this.errorMessage && (h("x-alert", { key: '5c252ae82688109aee3d4d38f0abfe17917c0676', small: true, color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: '49657406edc2fa81a35ba60d34d90fdfc5c47111', loading: !this.galleryUploadProgress, value: this.galleryUploadProgress })), h("x-tab", { key: '24acc4d0c4ce4b8a201b314eeafc26604963ee4d', label: Lang.get('gallery.generate') }, h("x-input", { key: '12aa11b5ab3d9929e14f49ac25276b0da1ed0b34', ref: el => (this.promptInput = el), placeholder: Lang.get('gallery.generate-placeholder') }, h("x-icon", { key: '97b2cd145fece42b49156f3a918f372e343835fc', name: "chatgpt", size: "24px", slot: "indicator" }), h("x-button", { key: '1e9b30ecb3076f29abcfb5463c5c1ec23a63bc26', icon: "right", slot: "buttons", onClick: () => this.onPromptImage(String(this.promptInput.value)) })), this.generatedCollection.length > 0 && h("x-divider", { key: '4f34d54bbe5e0d3016c1e46727eb01322cc7ddf0', class: "my-4" }, Lang.get('gallery.generated-images')), this.generatedCollection.length > 0 && (h("div", { key: 'a71f47a592cb1edcf6c6cfd377698162af133d96', 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: '29a64480eb6249bf594a807b2334151a276ce0cd', small: true, class: "mt-3", color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: 'e0a926962d4c39edc4d2c367ff11a5f8f7ed65ce', loading: true })))), h("x-dock", { key: '6eb989cb4e503da316af0de547373f943b59f441', block: true }, h("x-button", { key: 'b76f486e2542e173bed8e40582c491d0f6b6307e', icon: "left", onClick: () => this.onFinishSelectMedia() }, Lang.get('gallery.back')), h("x-button", { key: 'a094bb50c8a6e69dedb9d75ac6a5cb02929a6d17', 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": []
                }
            }
        };
    }
}
