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();
        this.image.$image.onload = () => {
            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);
            }
        };
    }
    /**
     * 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 = 44;
        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: '8ea79515897218e6903f1efb373bb1ea38ca9f77' }, h("x-modal", { key: '1df1e55cf9e4f41086be58bafea3bc38d2178fd2', ref: el => this.modal = el, closable: false, size: "full" }, h("div", { key: '890edc84baee36b60e8e0d04658b16e8bb00f9dd', class: "cropper-container", ref: el => this.container = el }, h("div", { key: '7a9eb696db83b886e6a3caa8fd31381fdf2f774a', class: cls('loading', { active: this.isLoading }) }, h("x-progress", { key: '66d9a1d0f227ef3728ba772d21ce042954ef16c5', loading: true })), h("div", { key: '3ae37cfa69d090b95ef8d34dd9514e024d3690c7', class: "preview", style: { display: this.isActivePreview ? 'block' : 'none' } }, h("div", { key: 'f7852117ec28c65132b3f47b84c88ae6b035dc46', class: "content" }, h("img", { key: '9be7bc164607a7b113abec85c39175be2e57ffd7', ref: el => this.preview = el, alt: "" }))), h("div", { key: '90f9357e0ba8a4cb70ad2e5574d355d1f0e490eb', class: cls('editor', { busy: this.isLoading }), style: { display: !this.isActivePreview ? 'block' : 'none' } }, h("canvas", { key: '43b20752b0b438da331a423eac98627338c2f780', ref: el => this.editor = el })), h("div", { key: '0a5d8f09816ab8caac95c7f5b2d184370dadd24d', class: "toolbar" }, h("div", { key: '53ed5d0eee2e5bf3bf8c34f49fbdd068d9107f6d', class: "message", style: { display: this.isActivePreview ? 'flex' : 'none' } }, h("p", { key: 'd19a9c1c6f7bf98389f5cff2de8247b6bf594294' }, Lang.get('cropper.preview_confirm_message'))), h("div", { key: '648507d34d923b78156705877550d90a45ed6d5a', class: "actions", style: { display: !this.isActivePreview ? 'flex' : 'none' } }, h("button", { key: '5eaaa97b8bf07b3ebac58de8e87a150cbf626ca0', 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: 'abc80d957e9e9faf2a010a911cf58334fc595122', size: "1.5rem", name: "plus" })), h("button", { key: '82d5bb7c1eb32fc48fce761473a58e74aa957dd8', 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: '3232eaefb80a1d841b0b4c49003d49c595c9b168', size: "1.5rem", name: "minus" })), h("button", { key: '6d9dff762d10a8a1a148982db27242e1ebfedf04', 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: '6edab404fc8a7bf73ca61f67efee20b6ff91b6b6', size: "1.5rem", name: "rotate-left" })), h("button", { key: '9f5165587a9052c9150dcfff578b71d23027037a', 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: 'fc73e739a64665579a47bc326afc39a01b4531aa', size: "1.5rem", name: "rotate-right" })), this.sizes.length > 1 && h("div", { key: '60f40176d3831e097d7f5052e59997ca8f674879', class: "separator" }), this.sizes.length > 1 && h("x-dropdown", { key: '12eed629174df6393965002b1223f97c113c89dd', align: "top-end", hover: true }, h("button", { key: 'e4e67c964fb3cc1c9880dfc0ca29cccbf703a1cc', class: "toolbar-button", type: "button" }, h("x-icon", { key: '20601b14ce50eb0bc6bb34c26644c66106c04a23', size: "1.5rem", name: "crop" })), h("ul", { key: '4cdd567bf80a3eb1628c2e32a7211acdc4787f14', 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("div", { key: '46a886155e50b520c476ee15da139aa524297809', class: "spacer" }), h("button", { key: 'db94e1fa371a297f439e75d1ba088ae455138f89', class: "toolbar-button", title: Lang.get('cropper.cancel'), type: "button", onClick: () => this.onReject() }, h("x-icon", { key: 'b9cc3cf4f89c16b8a313e3185ee4777dd72d1a97', size: "1.5rem", name: this.isActivePreview ? 'left' : 'trash' })), h("button", { key: '90306128c5175776d16681cd279da372044f7279', class: "toolbar-button last-child", title: Lang.get(this.isActivePreview ? 'cropper.confirm' : 'cropper.continue'), type: "button", onClick: () => this.onConfirm() }, h("x-icon", { key: 'c96bcd2faeaecb8db02848e6e766abded3ca55f0', size: "1.5rem", name: this.isActivePreview ? 'check' : 'right', color: "success" }))))));
    }
    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": []
                }
            }
        };
    }
}
