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();
        }
    }
    /**
     * 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: '8f9eef2715714eaafe61ed991eb96a2c8714f97d' }, h("x-modal", { key: '2fd4fadd48d3657ba0feb1c24707f8d8fa70d0f9', ref: el => this.modal = el, closable: false, size: "full" }, h("div", { key: '259e11f9838c754558ce1323eb231f9af1bf23f7', class: "cropper-container", ref: el => this.container = el }, h("div", { key: '53b9725cd176b1f068af77df716b41aae5080f23', class: cls('loading', { active: this.isLoading }) }, h("x-progress", { key: 'ce6c8613a497f0c9181a255a1f72924802dc63cb', loading: true })), h("div", { key: '7f0fefc5152688b0abe058d82df630ce76f9ca84', class: "preview", style: { display: this.isActivePreview ? 'block' : 'none' } }, h("div", { key: '36d3794af76c1495573b99c300e88c1d0093478a', class: "content" }, h("img", { key: '5195daf803b10ed9c003db5041dde715bf598749', ref: el => this.preview = el, alt: "" }))), h("div", { key: '1ce966c873f8e94fe58c0398944908ac6f83555c', class: cls('editor', { busy: this.isLoading }), style: { display: !this.isActivePreview ? 'block' : 'none' } }, h("canvas", { key: 'd48f5592a2c88ef73728053c58c960e443bbe598', ref: el => this.editor = el })), h("div", { key: 'f285d0071b2779957b459f9740d7b17051e63476', class: "toolbar" }, h("div", { key: '67d606e0a2a4e0aa5505dc38edf71c46470bc1ca', class: "message", style: { display: this.isActivePreview ? 'flex' : 'none' } }, h("p", { key: 'ff618bcdd568cfb329ce8ca2fe27b3fed421c575' }, Lang.get('cropper.preview_confirm_message'))), h("div", { key: '505cfbb97577c6ab218d91014e92515b3b98dfda', class: "actions", style: { display: !this.isActivePreview ? 'flex' : 'none' } }, h("button", { key: 'eea4702b6b5ca30ad005145903a87686cffdb230', 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: 'faf4c211a3f8273baea3f07c8c50738ca19e572e', size: "1.5rem", name: "plus" })), h("button", { key: '255aa9dfe0f5e273361c1e6fab166970567525c8', 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: 'c25f346464548b1f38a12a9177490664b2932da8', size: "1.5rem", name: "minus" })), h("button", { key: '7d33147f8ab0fdc4786775465118c4330e09cdee', 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: '799d10116f03ef70db7449a2a050a06ef8652b73', size: "1.5rem", name: "rotate-left" })), h("button", { key: 'db71e7568e7daf78e2b8d883e39ba855249c8587', 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: '0f3f44f411137a8f8decfdaf66371a01c38f28a0', size: "1.5rem", name: "rotate-right" })), this.sizes.length > 1 && h("div", { key: '9bd455d495fd68a9be3379a9f0fc0edf2bd07c88', class: "separator" }), this.sizes.length > 1 && h("x-dropdown", { key: 'b4bb6cdf7006c0789afb5dd0ffe6c8dfb8b7446c', align: "top-end", hover: true }, h("button", { key: '8a53fd4fae3a5fabdeaf5fa68498cebb910d6e67', class: "toolbar-button", type: "button" }, h("x-icon", { key: '653c26ca778bb9dc1ee53b0374bc6d5b83302571', size: "1.5rem", name: "crop" })), h("ul", { key: '6a40f3b3b0c61ec2a5079d0db1204a3692a636bd', 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: 'b756996368bb1cdf0109e4c7c7c606a89e4d43c4', class: "spacer" }), h("button", { key: 'c45f7ed7b0853fc91fb5716cf1d695eff0b7b69b', class: "toolbar-button", title: Lang.get('cropper.cancel'), type: "button", onClick: () => this.onReject() }, h("x-icon", { key: 'fed237976f212b77359f2c1606a21dcfaf06fd56', size: "1.5rem", name: this.isActivePreview ? 'left' : 'trash' })), h("button", { key: '682332eb3995fd9eff8e4a7be30ca760f0ddd170', class: "toolbar-button last-child", title: Lang.get(this.isActivePreview ? 'cropper.confirm' : 'cropper.continue'), type: "button", onClick: () => this.onConfirm() }, h("x-icon", { key: '9d684156ef38f3c0f39db6ef45a7408234a79645', 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"
                        }
                    }
                }
            }];
    }
    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": []
                }
            }
        };
    }
}
