import { Host, h } from "@stencil/core";
import { Lang } from "../../services/lang";
import { tinyMDtoHTML } from "../../utils/helpers";
import axios from "axios";
const GALLERY_ROUTE = '/services/media';
export class XGallery {
    constructor() {
        this.loading = false;
        this.errorMessage = undefined;
        this.selectedMedia = undefined;
        this.galleryCollection = [];
        this.galleryPage = 1;
        this.galleryResultsCount = 0;
        this.galleryHasMore = false;
        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: `${GALLERY_ROUTE}/gallery?page=${page}`,
        })
            .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: `${GALLERY_ROUTE}/generate`,
        })
            .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) {
        this.galleryCollection.unshift({
            uuid: 'upload-image',
            url: URL.createObjectURL(e.detail),
            type: 'image',
            loading: true,
        });
        this.errorMessage = null;
        this.loading = true;
        const data = new FormData();
        data.append('image', e.detail);
        axios({
            method: 'POST',
            url: `${GALLERY_ROUTE}/gallery`,
            data: data,
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            this.galleryCollection.shift();
            this.galleryCollection.unshift(data);
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * Delete image and return confirmation
     */
    onDeleteImage(uuid) {
        this.errorMessage = null;
        this.loading = true;
        axios({
            method: 'DELETE',
            url: `${GALLERY_ROUTE}/gallery?uuid=${uuid}`,
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            this.galleryCollection.splice(this.getIndexCollectionByUUID(this.galleryCollection, data.uuid), 1);
            this.selectedMedia = null;
        })
            .catch(err => {
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * Send IA prompt and return image result
     */
    onPromptImage(prompt) {
        this.generatedCollection.unshift({
            uuid: 'generate-image',
            url: '',
            type: 'image',
            loading: true,
        });
        this.errorMessage = null;
        this.loading = true;
        const data = new FormData();
        data.append('prompt', prompt);
        axios({
            method: 'POST',
            url: `${GALLERY_ROUTE}/generate`,
            data: data,
        })
            .then(response => {
            return response.data.data;
        })
            .then(data => {
            this.generatedCollection.shift();
            this.generatedCollection.unshift(data);
        })
            .catch(err => {
            this.generatedCollection.shift();
            this.errorMessage = this.catchRequestFail(err);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    /**
     * 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: '2192552d1069545045b372ac98a40329f439c4bc' }, h("x-modal", { key: 'd5ce6b72892336cc5e8c2a56dd874680c9e5051c', class: "image-gallery-modal", ref: el => (this.modal = el), closable: false, size: "big" }, h("x-card", { key: '79fbaa56f37b6f1f3d0be06fb60a5abcc51823a2', icon: "image-gallery", "icon-color": "primary", class: "gallery-picker" }, h("x-tabs", { key: '5b8c039aa7883dda83d9b51603938752503a4475' }, h("x-tab", { key: 'ce08a601c4ffbbd04101f008f84bbe3bd9830f7c', label: Lang.get('gallery.gallery'), badge: ((_a = this.selectedMedia) === null || _a === void 0 ? void 0 : _a.type) == 'image' ? 1 : null }, h("div", { key: '4e1da3b8c43c5c2184aa6a0aefe65509c39d3b0b', class: "items" }, h("x-input-image", { key: '2601f106ac9d5627a7dc0f57fbb9d3122fa6c993', ref: el => this.inputImage = el, "without-preview": true, onFile: e => this.onUploadImage(e) }, h("x-cropper", { key: '1d2d7fe9050a3666288a2b53f8c4395182c3f920' })), this.galleryCollection.map(item => {
            var _a;
            return (h("x-gallery-image", { url: item.url, key: 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: 'd07ef6e0978c935380bf7b19f43e410dd1aa92ce', align: "center" }, h("a", { key: 'd83cef808d902eb91e1a40d4fd75db1a519adcc0', href: "#", class: { disabled: this.loading }, onClick: () => this.loadGalleryAssets(this.galleryPage + 1) }, Lang.get('gallery.view-more')))), !!this.galleryResultsCount && !this.loading && (h("div", { key: 'e3d0a1a1cca307bfec54d1b12e5faa12709d25cd', class: "results mt-4", innerHTML: tinyMDtoHTML(Lang.get('gallery.gallery-results', {
                length: this.galleryCollection.length,
                total: this.galleryResultsCount,
            })) })), this.errorMessage && (h("x-alert", { key: 'f62fb4019758d057a945bbd067775c803934d069', small: true, color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: '24d38da797eab4bae3142ad2d7fe9528b3ef44d8', loading: true })), h("x-tab", { key: '3a5c568fd0d5691887e59c127d601e243561bdb3', label: Lang.get('gallery.generate') }, h("x-input", { key: '7743785413aed141972ea6419ceb1f8d6aaab956', ref: el => (this.promptInput = el), placeholder: Lang.get('gallery.generate-placeholder') }, h("x-icon", { key: 'e2dfa54b037c2d5ccfd61978be72ef9fefdab9ba', name: "chatgpt", size: "24px", slot: "indicator" }), h("x-button", { key: 'b45d6a907001a0d4a299b44dd8b6bd01952fac56', icon: "right", slot: "buttons", onClick: () => this.onPromptImage(String(this.promptInput.value)) })), this.generatedCollection.length > 0 && h("x-divider", { key: 'd543afd0df3e2338826c8670c684164140a0f8a0', class: "my-4" }, Lang.get('gallery.generated-images')), this.generatedCollection.length > 0 && (h("div", { key: '7b94b50e19e41e88d0034d29e137a0aa6cb36761', class: "items" }, this.generatedCollection.map(item => {
            var _a;
            return (h("x-gallery-image", { url: item.url, key: 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: '709e07d86b2eb02932e0ef57335c8a2196206f86', small: true, class: "mt-3", color: "danger", icon: "danger" }, this.errorMessage)), this.loading && h("x-progress", { key: 'fdac01d4517cddd04e57db48a266b905938796b7', loading: true }))), h("x-card-segment", { key: '46568b4e873ca9aab695527834991140ab02cbd5', slot: "footer", tinted: true }, h("x-button", { key: '9575e338cde14e2e307f298decf2f68ffcb73804', small: true, icon: "left", onClick: () => this.onFinishSelectMedia() }, Lang.get('gallery.back')), h("x-button", { key: '467c7f6ff7e04cd64a084329e560569f38d15eda', 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 states() {
        return {
            "loading": {},
            "errorMessage": {},
            "selectedMedia": {},
            "galleryCollection": {},
            "galleryPage": {},
            "galleryResultsCount": {},
            "galleryHasMore": {},
            "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": []
                }
            }
        };
    }
}
