import { Host, h } from "@stencil/core";
import Cropper from "cropperjs";
import { Lang } from "../../services/lang";
import { cls, getRemPixels } from "../../utils/helpers";
import { Theme } from "../../services/theme";
export class XCropper {
    constructor() {
        this.isLoading = undefined;
        this.isActivePreview = undefined;
        this.sizes = [];
        this.activeSize = undefined;
    }
    /**
     * Call the cropper window
     */
    async load(options) {
        var _a;
        this.loadImage(options.source);
        this.sizes = (_a = options.sizes) !== null && _a !== void 0 ? _a : [];
        this.isLoading = true;
        this.modal.open();
        this.image.$ready().then(() => {
            var _a;
            this.image.$center('contain');
            if ((_a = this.sizes) === null || _a === void 0 ? void 0 : _a.length) {
                this.onSetSize(this.sizes[0]);
            }
            setTimeout(() => {
                this.isLoading = false;
            }, 1000);
        }).catch(err => {
            this.isLoading = false;
            this.modal.close();
            window.notification.fail(err, null, null, 5);
        });
    }
    /**
     * On component loaded action
     */
    componentDidLoad() {
        this.cropper = new Cropper(this.editor);
        this.image = this.cropper.getCropperImage();
        this.selection = this.cropper.getCropperSelection();
        const init = () => {
            var _a;
            this.resizeEditor();
            if ((_a = this.sizes) === null || _a === void 0 ? void 0 : _a.length) {
                this.onSetSize(this.sizes[0]);
            }
            else {
                const canvas = this.cropper.getCropperCanvas();
                this.selection.width = parseInt(canvas.style.width) / 2;
                this.selection.height = parseInt(canvas.style.height) / 2;
                setTimeout(() => this.selection.$center(), 300);
            }
        };
        window.addEventListener('resize', init);
        this.image.$image.onload = init;
    }
    /**
     * Prepare the image to cropper by source type
     */
    loadImage(source) {
        if (source instanceof File) {
            const reader = new FileReader();
            reader.onload = () => {
                if (typeof reader.result === 'string') {
                    this.image.$image.src = reader.result;
                }
            };
            reader.readAsDataURL(source);
        }
        else {
            this.image.$image.src = source;
        }
    }
    resizeEditor() {
        const rem = getRemPixels();
        const toolbarHeight = rem + 50 + rem;
        const bounds = {
            imageWidth: this.image.$image.naturalWidth,
            imageHeight: this.image.$image.naturalWidth,
            maxWidth: document.documentElement.clientWidth - (Theme.isMobile() ? 0 : rem * 2),
            maxHeight: document.documentElement.clientHeight - (Theme.isMobile() ? 0 : rem * 2) - toolbarHeight,
            minWidth: 300,
            minHeight: 100,
        };
        let canvasWidth = Math.max(bounds.minWidth, Math.min(bounds.imageWidth, bounds.maxWidth));
        let canvasHeight = Math.max(bounds.minHeight, Math.min(bounds.imageHeight, bounds.maxHeight));
        const canvas = this.cropper.getCropperCanvas();
        canvas.style.width = Theme.isMobile() ? `${document.documentElement.clientWidth}px` : `${canvasWidth}px`;
        canvas.style.height = `${canvasHeight}px`;
        this.container.style.maxWidth = Theme.isMobile() ? '100%' : `${canvasWidth}px`;
        this.image.$center('contain');
    }
    onReject() {
        if (this.isActivePreview) {
            this.isActivePreview = false;
            this.resizeEditor();
        }
        else {
            this.modal.close();
            this.onClose.emit();
        }
    }
    /**
     * Show the confirmation window before dispatch success event
     */
    onConfirm() {
        this.isLoading = true;
        this.cropper
            .getCropperSelection()
            .$toCanvas(this.activeSize ?
            {
                width: this.activeSize.width,
                height: this.activeSize.height,
            } : null)
            .then(canvas => {
            if (this.isActivePreview) {
                this.onCropped.emit(canvas);
                this.modal.close();
                setTimeout(() => {
                    this.isActivePreview = false;
                    this.isLoading = false;
                }, 300);
            }
            else {
                const rem = getRemPixels();
                const preview = this.container.querySelector('.preview .content');
                const width = this.activeSize ? this.activeSize.width : this.selection.width;
                preview.style.width = `${Math.max(width, 300)}px`;
                this.container.style.maxWidth = Theme.isMobile() ? null : `${Math.max(width, 300) + rem}px`;
                this.preview.src = canvas.toDataURL();
                this.isActivePreview = true;
                this.isLoading = false;
            }
        })
            .catch(err => {
            this.isLoading = false;
            window.notification.fail(err, null, null, 5);
        });
    }
    onSetSize(size) {
        var _a;
        this.activeSize = size;
        this.selection.aspectRatio = size.width / size.height;
        (_a = this.selection) === null || _a === void 0 ? void 0 : _a.$change(0, 0, size.width, size.height).$center();
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: '233b94a05bda2e4cff856e2b113d0a6b4e7eebe9' }, h("x-modal", { key: 'eb479b2eeea6816c9ff0b8a1131788dbb6a0736e', ref: el => this.modal = el, closable: false, size: this.isActivePreview ? 'auto' : 'full' }, h("div", { key: 'abeb5d0838da599ba189cd301761832126af8502', class: "cropper-container", ref: el => this.container = el }, h("div", { key: 'bddfc3d97f739a1ba54d39a689c1456faf9fdcd3', class: cls('loading', { active: this.isLoading }) }, h("x-progress", { key: '946dfd407033f0208cb519a909e2c840b1ddcfed', loading: true })), h("div", { key: '286a1677bd1f9b956516a1c15831df37890a6993', class: "preview", style: { display: this.isActivePreview ? 'block' : 'none' } }, h("div", { key: 'b0cbe3a032adfff62afa28b255322098a39a5ade', class: "content" }, h("img", { key: 'c9c6d97b4e7d3a5d39dbf4295a957ac600f50b9d', ref: el => this.preview = el, alt: "" })), h("p", { key: '1e17b38f7ed5a4d9c60bba6818794d0445ae99f8' }, Lang.get('cropper.preview_confirm_message'))), h("div", { key: 'e38b3448c6a519b16a032471e21325c82b2a4971', class: cls('editor', { busy: this.isLoading }), style: { display: !this.isActivePreview ? 'block' : 'none' } }, h("canvas", { key: '1fb928f81745bb55db287de3a5b69e58d559d2e7', ref: el => this.editor = el })), h("div", { key: '6169d7d712740b172440aea2bb3bf2234cf448e7', class: "toolbar" }, h("div", { key: 'ecf9adc3ec11992e7c5c0e663c0bb29baddfafef', class: "actions", style: { display: !this.isActivePreview ? 'flex' : 'none' } }, h("button", { key: 'beada2e939ccec6cdd2379c344f9df6a483a5b74', class: "toolbar-button first-child", type: "button", title: Lang.get('cropper.zoom_in'), onClick: () => { var _a; return (_a = this.image) === null || _a === void 0 ? void 0 : _a.$zoom(0.1); } }, h("x-icon", { key: 'f4dcbf97f546f957c736e8dc26d9a4cb552d34ca', size: "1.5rem", name: "plus" })), h("button", { key: '7a85187c2cd78569574c360fae51278cf575ed2e', class: "toolbar-button", type: "button", title: Lang.get('cropper.zoom_out'), onClick: () => { var _a; return (_a = this.image) === null || _a === void 0 ? void 0 : _a.$zoom(-0.1); } }, h("x-icon", { key: '0fb031719a7eb9cca089993d5a7fe2ccca28219c', size: "1.5rem", name: "minus" })), h("button", { key: '83a969866ad544c26bbae045c8692be2e60296c0', class: "toolbar-button", type: "button", title: Lang.get('cropper.center'), onClick: () => { var _a; return (_a = this.image) === null || _a === void 0 ? void 0 : _a.$center('contain'); } }, h("x-icon", { key: 'ded0ece81526da6b40e38241bf1ff2f3ccac9ca4', size: "1.5rem", name: "move" })), h("button", { key: '5307295a45c34cef586383afac026531efc6c0d7', class: "toolbar-button", type: "button", title: Lang.get('cropper.rotate_left'), onClick: () => { var _a; return (_a = this.image) === null || _a === void 0 ? void 0 : _a.$rotate('-90deg'); } }, h("x-icon", { key: 'f102730106ce85c61e9053ba98a539e268c5cb6b', size: "1.5rem", name: "rotate-left" })), h("button", { key: 'e41f7263064831193635bdc59dffc0b242f8550f', class: "toolbar-button", type: "button", title: Lang.get('cropper.rotate_right'), onClick: () => { var _a; return (_a = this.image) === null || _a === void 0 ? void 0 : _a.$rotate('90deg'); } }, h("x-icon", { key: 'acf3fd3bdd140ca3ccbdf581c674b779ff4a7cd7', size: "1.5rem", name: "rotate-right" })), this.sizes.length > 1 && h("div", { key: 'f6faed48873c61a55df52ee970991262ea489278', class: "separator" }), this.sizes.length > 1 && h("x-dropdown", { key: '6d0faa64128f85512d902a94fc53781f406b0bf6', align: "top-end", hover: true }, h("button", { key: 'e636ba67d459688b31ebbafd901459013cacf453', class: "toolbar-button", type: "button" }, h("x-icon", { key: 'c385c6b2a8c11644ed4ee4fe2c389c03ff564a5f', size: "1.5rem", name: "crop" })), h("ul", { key: 'cee7536983b068c37a0069119cc01ca923f3682e', class: "sizes", slot: "dropdown" }, this.sizes.map(size => h("li", { class: cls({ active: this.activeSize == size }) }, h("button", { onClick: () => this.onSetSize(size) }, h("span", null, size.label), h("small", null, size.width, " x ", size.height))))))))), h("x-dock", { key: '0bb3c80f4364bb7d4c0e81dafbc0a260911eefbc', block: true }, h("x-button", { key: '2c0c1c36156fd08adcdd963712182d509440a2ab', icon: this.isActivePreview ? 'left' : 'trash', onClick: () => this.onReject() }, Lang.get('cropper.cancel')), h("x-button", { key: '3162fae70061506dc4a220491bdcfca9a1de31a8', color: "primary", icon: this.isActivePreview ? 'check' : 'right', onClick: () => this.onConfirm() }, Lang.get(this.isActivePreview ? 'cropper.confirm' : 'cropper.continue')))));
    }
    static get is() { return "x-cropper"; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "isActivePreview": {},
            "sizes": {},
            "activeSize": {}
        };
    }
    static get events() {
        return [{
                "method": "onCropped",
                "name": "cropped",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On cropped result image event"
                },
                "complexType": {
                    "original": "HTMLCanvasElement",
                    "resolved": "HTMLCanvasElement",
                    "references": {
                        "HTMLCanvasElement": {
                            "location": "global",
                            "id": "global::HTMLCanvasElement"
                        }
                    }
                }
            }, {
                "method": "onClose",
                "name": "close",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On cropped result image event"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "load": {
                "complexType": {
                    "signature": "(options: CropperOptions) => Promise<void>",
                    "parameters": [{
                            "name": "options",
                            "type": "{ source: string | File; sizes?: CropperSizeOption[]; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "CropperOptions": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-cropper/component.tsx",
                            "id": "src/components/x-cropper/component.tsx::CropperOptions"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Call the cropper window",
                    "tags": []
                }
            }
        };
    }
}
