import { Host, h, } from "@stencil/core";
import authStore, { EzpAuthorizationService, sendCodeToParentWindow } from "../../services/auth";
import printStore, { EzpPrintService } from "../../services/print";
import userStore from "../../services/user";
import config from "../../shared/config.json";
import i18next from "i18next";
import { initi18n } from "../../utils/utils";
export class EzpPrinting {
    constructor() {
        this.filename = '';
        this.hidemenu = false;
        this.hideheader = false;
        this.theme = 'cyan';
        this.appearance = 'system';
        this.language = '';
        this.seamless = false;
        /**
         *
         * States
         *
         */
        /** Description... */
        this.printOpen = false;
        this.authOpen = false;
        this.onlyGetSasUri = false;
        this.noDocumentOpen = false;
        this.files = [];
    }
    /** Watchers */
    watchFileData(newValue, oldValue) {
        console.log(newValue);
        if (newValue !== oldValue && newValue.length > 0) {
            let array = new Uint8Array(newValue.length);
            for (let i = 0; i < newValue.length; i++) {
                array[i] = newValue.charCodeAt(i);
            }
            this.files = [new File([array], this.filename)];
        }
    }
    watchFilename(newValue, oldValue) {
        if (newValue !== oldValue && newValue.length > 0) {
            this.filename = newValue;
        }
    }
    watchFileUrl(newValue, oldValue) {
        if (newValue !== oldValue && newValue.length > 0) {
            this.fileurl = newValue;
        }
    }
    watchLanguage(newValue, oldValue) {
        if (newValue !== oldValue && newValue.length > 0) {
            this.language = newValue;
        }
    }
    /**
     *
     * Listeners
     *
     */
    /** Description... */
    listenPrintCancel() {
        this.printOpen = false;
        // Clear the selected files and reset the upload component
        this.files = [];
        this.filename = '';
        // Emit printCancel to reset the upload component
        const printCancelEvent = new CustomEvent('printCancel', {
            bubbles: true,
            detail: {},
        });
        document.dispatchEvent(printCancelEvent);
        this.printFinished.emit();
    }
    /** Description... */
    listenPrintSubmit() {
        this.printOpen = false;
        this.printFinished.emit();
        this.checkAuth();
    }
    /** Description... */
    listenAuthCancel() {
        this.authOpen = false;
        this.checkAuth();
    }
    listenUserCancel() {
        this.authOpen = false;
        // Clear the selected files and reset the upload component
        this.files = [];
        this.filename = '';
        // Emit printCancel to reset the upload component
        const printCancelEvent = new CustomEvent('printCancel', {
            bubbles: true,
            detail: {},
        });
        document.dispatchEvent(printCancelEvent);
        this.checkAuth();
    }
    listenAuthSuccess() {
        if (this.onlyGetSasUri) {
            this.printOpen = false;
            this.onlyGetSasUri = false;
        }
        else if (this.filename != '') {
            this.printOpen = true;
        }
        else {
            this.noDocumentOpen = true;
        }
    }
    listenUploadFile(event) {
        this.files = event.detail;
        this.filename = this.files.length > 0 ? this.files[0].name : '';
        this.open();
    }
    listenDialogClose(event) {
        if (event.detail === 'no-document-selected') {
            this.noDocumentOpen = false;
        }
    }
    listenDialogAction(event) {
        if (event.detail === 'no-document-selected') {
            this.noDocumentOpen = false;
        }
    }
    listenLogout() {
        this.logOut();
    }
    /**
     *
     * Public methods
     *
     */
    async open() {
        // Always show auth dialog when files are uploaded to give users cancel option
        // Even if already authenticated, show the auth component for consistency
        this.authOpen = true;
    }
    async logOut() {
        this.auth.revokeRefreshToken();
        localStorage.removeItem('properties');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('access_token');
        localStorage.removeItem('printer');
        localStorage.removeItem('isAuthorized');
        this.printOpen = false;
    }
    async getSasUri() {
        this.onlyGetSasUri = true;
        const printService = new EzpPrintService(this.redirecturi, this.clientid);
        let response = await printService.prepareFileUpload(authStore.state.accessToken).catch(() => {
            this.open();
            return null;
        });
        if (response) {
            const sasUri = response.sasUri;
            return sasUri;
        }
    }
    async getAuthUri() {
        this.auth.generateCodeVerifier();
        await this.auth.generateCodeChallenge(authStore.state.codeVerifier);
        this.auth.buildAuthURI();
        return authStore.state.authUri;
    }
    async setAuthRefreshToken(refreshToken) {
        // Store the refresh token in the same way as the component does in self-managed auth
        authStore.state.refreshToken = refreshToken;
        localStorage.setItem('refreshToken', refreshToken);
        // Use the refresh token to obtain a valid access token
        // This ensures the user doesn't see the login dialog
        await this.auth.refreshTokens();
    }
    async checkAuth() {
        const printService = new EzpPrintService(this.redirecturi, this.clientid);
        let accessToken = authStore.state.accessToken;
        if (accessToken === '') {
            accessToken = localStorage.getItem('access_token');
            authStore.state.accessToken = accessToken;
        }
        if (localStorage.getItem('isAuthorized')) {
            authStore.state.isAuthorized = localStorage.getItem('isAuthorized') === 'true';
        }
        await printService
            .getConfig(authStore.state.accessToken)
            .then((response) => {
            if (response.ok) {
                authStore.state.isAuthorized = true;
            }
            if (!response.ok) {
                authStore.state.isAuthorized = false;
                throw new Error('http status ' + response.status);
            }
        })
            .catch(() => {
            authStore.state.isAuthorized = false;
        });
        localStorage.setItem('isAuthorized', authStore.state.isAuthorized.toString());
        return authStore.state.isAuthorized;
    }
    /**
     * Normalizes a URL or hostname to just the hostname without protocol
     * Accepts both "hostname" and "https://hostname" formats
     */
    normalizeHostUrl(hostUrl) {
        if (!hostUrl) {
            return hostUrl;
        }
        // If it starts with http:// or https://, extract just the hostname
        try {
            if (hostUrl.startsWith('http://') || hostUrl.startsWith('https://')) {
                const url = new URL(hostUrl);
                return url.host;
            }
        }
        catch (e) {
            // If URL parsing fails, return the original value
            console.warn('Failed to parse URL:', hostUrl, e);
        }
        // Return as-is if it's already just a hostname
        return hostUrl;
    }
    refreshTokensPeriodically(seconds) {
        const authService = new EzpAuthorizationService(this.redirecturi, this.clientid);
        setInterval(() => {
            authService.refreshTokens();
        }, seconds * 1000);
    }
    async componentWillLoad() {
        const systemAppearanceDark = window.matchMedia('(prefers-color-scheme: dark)');
        this.systemAppearance = systemAppearanceDark.matches ? 'dark' : 'light';
        systemAppearanceDark.addEventListener('change', (event) => {
            this.systemAppearance = event.matches ? 'dark' : 'light';
        });
        authStore.state.redirectUri = this.redirecturi;
        userStore.state.theme = this.theme;
        userStore.state.appearance = this.appearance;
        if (this.authapihosturl) {
            authStore.state.authApiHostUrl = this.normalizeHostUrl(this.authapihosturl);
        }
        else {
            authStore.state.authApiHostUrl = config.authApiHostUrl;
        }
        if (this.printapihosturl) {
            printStore.state.printApiHostUrl = this.normalizeHostUrl(this.printapihosturl);
        }
        else {
            printStore.state.printApiHostUrl = config.printingApiHostUrl;
        }
        this.auth = new EzpAuthorizationService(this.redirecturi, this.clientid);
        sendCodeToParentWindow();
        initi18n(this.language);
        this.checkAuth();
    }
    componentDidLoad() {
        this.refreshTokensPeriodically(1800);
    }
    /**
     *
     * Render method
     *
     */
    render() {
        return (h(Host, { key: 'd18dece1239b7557c5f80198637a828cbb4e820d', class: `${userStore.state.theme} ${userStore.state.appearance === 'system'
                ? this.systemAppearance
                : userStore.state.appearance} ${this.seamless ? 'seamless' : ''}` }, this.trigger === 'custom' ? (h("slot", null)) : this.trigger === 'file' ? (h("ezp-upload", null)) : (this.trigger === 'button' && (h("ezp-icon-button", { id: "print-trigger", icon: "printer", slot: "trigger", type: "button", onClick: () => this.open() }))), this.authOpen ? (h("ezp-auth", { clientID: this.clientid, redirectURI: this.redirecturi, hidelogin: this.hidelogin, trigger: this.trigger, code: this.code })) : this.printOpen ? (h("ezp-printer-selection", { clientID: this.clientid, redirectURI: this.redirecturi, filename: this.filename, fileurl: this.fileurl, filetype: this.filetype, fileid: this.fileid, files: this.files, hidemenu: this.hidemenu, hideheader: this.hideheader, seamless: this.seamless })) : this.noDocumentOpen ? (h("ezp-dialog", { heading: i18next.t('no_document_dialog.heading'), description: i18next.t('no_document_dialog.description'), action: i18next.t('no_document_dialog.action'), iconName: "question-mark", instance: "no-document-selected" })) : null));
    }
    static get is() { return "ezp-printing"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ezp-printing.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ezp-printing.css"]
        };
    }
    static get properties() {
        return {
            "clientid": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "clientid"
            },
            "redirecturi": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "redirecturi"
            },
            "filename": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "filename",
                "defaultValue": "''"
            },
            "fileurl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "fileurl"
            },
            "filetype": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "filetype"
            },
            "custom": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom"
            },
            "hidelogin": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hidelogin"
            },
            "hidemenu": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hidemenu",
                "defaultValue": "false"
            },
            "hideheader": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "hideheader",
                "defaultValue": "false"
            },
            "authapihosturl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "authapihosturl"
            },
            "printapihosturl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "printapihosturl"
            },
            "theme": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "ThemeTypes",
                    "resolved": "\"blue\" | \"cyan\" | \"green\" | \"orange\" | \"pink\" | \"red\" | \"teal\" | \"violet\"",
                    "references": {
                        "ThemeTypes": {
                            "location": "import",
                            "path": "./../../shared/types",
                            "id": "src/shared/types.d.ts::ThemeTypes",
                            "referenceLocation": "ThemeTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "theme",
                "defaultValue": "'cyan'"
            },
            "fileid": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "fileid"
            },
            "appearance": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "AppearanceTypes",
                    "resolved": "\"dark\" | \"light\" | \"system\"",
                    "references": {
                        "AppearanceTypes": {
                            "location": "import",
                            "path": "./../../shared/types",
                            "id": "src/shared/types.d.ts::AppearanceTypes",
                            "referenceLocation": "AppearanceTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "appearance",
                "defaultValue": "'system'"
            },
            "trigger": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "TriggerTypes",
                    "resolved": "\"button\" | \"custom\" | \"file\"",
                    "references": {
                        "TriggerTypes": {
                            "location": "import",
                            "path": "./../../shared/types",
                            "id": "src/shared/types.d.ts::TriggerTypes",
                            "referenceLocation": "TriggerTypes"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "trigger"
            },
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "language",
                "defaultValue": "''"
            },
            "code": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "code"
            },
            "filedata": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "filedata"
            },
            "seamless": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "seamless",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "printOpen": {},
            "authOpen": {},
            "onlyGetSasUri": {},
            "noDocumentOpen": {},
            "systemAppearance": {},
            "files": {}
        };
    }
    static get events() {
        return [{
                "method": "printFinished",
                "name": "printFinished",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Events"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "open": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "\nPublic methods",
                    "tags": []
                }
            },
            "logOut": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "getSasUri": {
                "complexType": {
                    "signature": "() => Promise<string>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "getAuthUri": {
                "complexType": {
                    "signature": "() => Promise<string>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "setAuthRefreshToken": {
                "complexType": {
                    "signature": "(refreshToken: string) => Promise<void>",
                    "parameters": [{
                            "name": "refreshToken",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "checkAuth": {
                "complexType": {
                    "signature": "() => Promise<boolean>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<boolean>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get watchers() {
        return [{
                "propName": "filedata",
                "methodName": "watchFileData"
            }, {
                "propName": "filename",
                "methodName": "watchFilename"
            }, {
                "propName": "fileurl",
                "methodName": "watchFileUrl"
            }, {
                "propName": "language",
                "methodName": "watchLanguage"
            }];
    }
    static get listeners() {
        return [{
                "name": "printCancel",
                "method": "listenPrintCancel",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "printSubmit",
                "method": "listenPrintSubmit",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "authCancel",
                "method": "listenAuthCancel",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "userCancel",
                "method": "listenUserCancel",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "authSuccess",
                "method": "listenAuthSuccess",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "uploadFile",
                "method": "listenUploadFile",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "dialogClose",
                "method": "listenDialogClose",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "dialogAction",
                "method": "listenDialogAction",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "logout",
                "method": "listenLogout",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
