import { getTranslations } from "../../utils/locale.utils";
import { h } from "@stencil/core";
import { io } from "socket.io-client";
import { Build } from "@stencil/core";
import { initializeSession } from "../../api/methods";
import { notificationCache } from "../../cache";
export class NutsInboxWidget {
    constructor() {
        this.token = null;
        this.baseUrl = `${this.backendUrl}/v1/${this.operatorId}`;
        this.initializeSessionBody = {
            applicationIdentifier: this.applicationIdentifier,
            subscriberId: this.subscriberId || `${this.operatorId}-${this.userId}`,
            hmacHash: null,
            language: this.language,
            deviceId: this.deviceId
        };
        this.togglePopover = () => {
            this.popoverVisible = !this.popoverVisible;
            if (!Build.isBrowser)
                return;
            window.postMessage({ type: 'nuts-popover-isVisible', value: this.popoverVisible }, window.location.href);
        };
        this.setClientStyling = () => {
            let sheet = document.createElement('style');
            sheet.innerHTML = this.clientStyling;
            this.stylingContainer.prepend(sheet);
        };
        this.setClientStylingURL = () => {
            if (!Build.isBrowser)
                return;
            let url = new URL(this.clientStylingUrl);
            let cssFile = document.createElement('style');
            fetch(url.href)
                .then((res) => res.text())
                .then((data) => {
                cssFile.innerHTML = data;
                this.clientStyling = data;
                setTimeout(() => {
                    this.stylingContainer.prepend(cssFile);
                }, 1);
            })
                .catch((err) => {
                console.log('error ', err);
            });
        };
        this.assignRefToStylingContainer = (ref) => {
            this.stylingContainer = ref;
        };
        this.assignRefToBell = (ref) => {
            this.bellIconRef = ref;
        };
        this.backendUrl = undefined;
        this.socketUrl = undefined;
        this.userId = undefined;
        this.sessionId = undefined;
        this.operatorId = undefined;
        this.subscriberId = undefined;
        this.deviceId = undefined;
        this.language = 'en';
        this.environment = 'stage';
        this.applicationIdentifier = undefined;
        this.clientStyling = '';
        this.clientStylingUrl = undefined;
        this.bellIconPosition = 'left';
        this.notificationAction = 'default';
        this.translationUrl = '';
        this.isLoading = false;
        this.popoverVisible = false;
        this.unseenCount = undefined;
    }
    initializeHandler(newValue, oldValue) {
        if (!Build.isBrowser)
            return;
        if (newValue !== oldValue) {
            if (this.subscriberId && this.operatorId && this.applicationIdentifier) {
                initializeSession({
                    baseUrl: this.baseUrl,
                    body: this.initializeSessionBody,
                    sessionId: this.sessionId
                }).then((initializeSessionResult) => {
                    this.token = initializeSessionResult.token;
                    this.unseenCount = initializeSessionResult.unseenCounter;
                    window.postMessage({ type: 'nuts-new-notifications', value: this.unseenCount }, window.location.href);
                    this.setupSocket();
                });
            }
        }
    }
    clickOutsideHandle(ev) {
        if (!Build.isBrowser)
            return;
        if (ev.composedPath().some((elem) => this.el === elem)) {
            return;
        }
        this.popoverVisible = false;
        window.postMessage({ type: 'nuts-popover-isVisible', value: this.popoverVisible }, window.location.href);
    }
    resetUnseenCount() {
        // reset the unseen count if all notif are marked as read
        this.unseenCount = 0;
        if (!Build.isBrowser)
            return;
        window.postMessage({ type: 'all-notifications-read', value: true }, window.location.href);
    }
    closePopoverHandler() {
        this.popoverVisible = false;
        if (!Build.isBrowser)
            return;
        window.postMessage({ type: 'nuts-popover-isVisible', value: this.popoverVisible }, window.location.href);
    }
    positionIcon() {
        if (this.bellIconPosition == 'left') {
            this.bellIconRef.style.justifyContent = 'flex-start';
        }
        if (this.bellIconPosition == 'right') {
            this.bellIconRef.style.justifyContent = 'flex-end';
        }
    }
    setupSocket() {
        if (!Build.isBrowser)
            return;
        if (this.socketRef)
            return;
        const { origin, pathname } = new URL(this.socketUrl);
        if (this.token) {
            this.socketRef = io(origin, Object.assign(Object.assign({ reconnection: true, reconnectionDelayMax: 10000, reconnectionAttempts: 10, transports: ['websocket'] }, (pathname ? { path: pathname + '/socket.io' } : {})), { auth: {
                    token: `${this.token}`
                } }));
            this.socketRef.on('connect_error', (error) => {
                console.error('WebSocket error', error);
            });
            this.socketRef.on('reconnect_attempt', (attemptNumber) => {
                console.log('Reconnect attempt', attemptNumber);
            });
            this.socketRef.on('notification_received', (data) => {
                this.newNotification.emit(data.message);
                notificationCache.addToFront(data.message);
            });
            this.socketRef.on('unseen_count_changed', (data) => {
                this.unseenCount = data.unseenCount;
                if (!Build.isBrowser)
                    return;
                window.postMessage({ type: 'nuts-new-notifications', value: this.unseenCount }, window.location.href);
            });
        }
    }
    async init() {
        if (!Build.isBrowser)
            return;
        if (this.subscriberId && this.operatorId && this.applicationIdentifier) {
            const initializeSessionResult = await initializeSession({
                baseUrl: this.baseUrl,
                body: this.initializeSessionBody,
                sessionId: this.sessionId
            });
            this.token = initializeSessionResult.token;
            this.unseenCount = initializeSessionResult.unseenCounter;
            window.postMessage({ type: 'nuts-new-notifications', value: this.unseenCount }, window.location.href);
            this.setupSocket();
        }
    }
    handleStylingChange(newValue, oldValue) {
        if (newValue !== oldValue)
            this.setClientStyling();
    }
    handleStylingUrlChange(newValue, oldValue) {
        if (newValue !== oldValue)
            this.setClientStylingURL();
    }
    handleNewTranslations() {
        this.isLoading = true;
        getTranslations(this.translationUrl).then(() => {
            this.isLoading = false;
        });
    }
    async componentWillLoad() {
        if (this.translationUrl.length > 2) {
            await getTranslations(this.translationUrl);
        }
    }
    componentDidRender() {
        this.positionIcon();
    }
    componentDidLoad() {
        this.init();
        if (this.clientStyling) {
            this.setClientStyling();
        }
        if (this.clientStylingUrl) {
            this.setClientStylingURL();
        }
    }
    renderBellIcon() {
        return (h("div", { onClick: this.togglePopover, class: "BellIcon" }, h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "32", height: "32", fill: "currentColor", class: "bi bi-bell", viewBox: "0 0 16 16" }, ' ', h("path", { d: "M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z" }), ' '), this.unseenCount > 0 ? (h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", class: "nc-bell-button-dot css-0 css-1eg2znq" }, h("rect", { x: "1.5", y: "1.5", width: "13", height: "13", rx: "6.5", fill: "url(#paint0_linear_1722_2699)", stroke: "#1E1E26", "stroke-width": "3" }), h("defs", null, h("linearGradient", { id: "paint0_linear_1722_2699", x1: "8", y1: "13", x2: "8", y2: "3", gradientUnits: "userSpaceOnUse" }, h("stop", { "stop-color": "#FF512F" }), h("stop", { offset: "1", "stop-color": "#DD2476" }))))) : ('')));
    }
    render() {
        return (h("div", { key: 'd8ba7712fa7436253806c2cd5700eb715f2791b4', ref: this.assignRefToStylingContainer, class: "Wrapper" }, h("div", { key: '0578f0a3d489685c76a921a71291976741c3d0e7', ref: this.assignRefToBell, class: "BellIconWrapper" }, !this.isLoading && this.renderBellIcon()), this.token && this.popoverVisible && (h("nuts-popover", { key: '3bbc22caa8689c29a098ef7308724d8a34289abc', "notification-action": this.notificationAction, sessionId: this.sessionId, "unseen-count": this.unseenCount, token: this.token, "backend-url": this.backendUrl, "operator-id": this.operatorId, "user-id": this.userId, language: this.language, "client-styling": this.clientStyling, "client-styling-url": this.clientStylingUrl, "translation-url": this.translationUrl }))));
    }
    static get is() { return "nuts-inbox-widget"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["nuts-inbox-widget.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["nuts-inbox-widget.css"]
        };
    }
    static get properties() {
        return {
            "backendUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "HTTP Endpoint URL for NuTS"
                },
                "attribute": "backend-url",
                "reflect": true
            },
            "socketUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Socket Endpoint URL for NuTS"
                },
                "attribute": "socket-url",
                "reflect": true
            },
            "userId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the user"
                },
                "attribute": "user-id",
                "reflect": true
            },
            "sessionId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The sessionID of the user"
                },
                "attribute": "session-id",
                "reflect": true
            },
            "operatorId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The operatorID on which we can find the user"
                },
                "attribute": "operator-id",
                "reflect": true
            },
            "subscriberId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The subscriberID"
                },
                "attribute": "subscriber-id",
                "reflect": true
            },
            "deviceId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The deviceID from which the user access the website"
                },
                "attribute": "device-id",
                "reflect": true
            },
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Language of the widget"
                },
                "attribute": "language",
                "reflect": true,
                "defaultValue": "'en'"
            },
            "environment": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Environment on which the widget is used (possible values: `stage`, `prod`)"
                },
                "attribute": "environment",
                "reflect": true,
                "defaultValue": "'stage'"
            },
            "applicationIdentifier": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Novu application identifier"
                },
                "attribute": "application-identifier",
                "reflect": true
            },
            "clientStyling": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Client custom styling via inline styles"
                },
                "attribute": "client-styling",
                "reflect": true,
                "defaultValue": "''"
            },
            "clientStylingUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Client styling url for a css file"
                },
                "attribute": "client-styling-url",
                "reflect": true
            },
            "bellIconPosition": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Position of the widget (possible values: `left` and `right`) - this changes the `justify-content` property of the `.BellIconWrapper` class"
                },
                "attribute": "bell-icon-position",
                "reflect": true,
                "defaultValue": "'left'"
            },
            "notificationAction": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Clicking on the notification will automatically redirect you to the redirectURL attached to the notification (`default` behaviour). It can be changed to `postMessage` and instead of the redirect it will emit a postMessage with the redirectURL and the parent website can take actions"
                },
                "attribute": "notification-action",
                "reflect": true,
                "defaultValue": "'default'"
            },
            "translationUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Translations via URL"
                },
                "attribute": "translation-url",
                "reflect": true,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "popoverVisible": {},
            "unseenCount": {}
        };
    }
    static get events() {
        return [{
                "method": "notificationFeed",
                "name": "notificationFeed",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "Notification[]",
                    "resolved": "Notification[]",
                    "references": {
                        "Notification": {
                            "location": "import",
                            "path": "../../types/nuts-inbox-widget.types",
                            "id": "../../../../packages/stencil/nuts-inbox-widget/src/types/nuts-inbox-widget.types.ts::Notification"
                        }
                    }
                }
            }, {
                "method": "newNotification",
                "name": "newNotification",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "subscriberId",
                "methodName": "initializeHandler"
            }, {
                "propName": "operatorId",
                "methodName": "initializeHandler"
            }, {
                "propName": "applicationIdentifier",
                "methodName": "initializeHandler"
            }, {
                "propName": "deviceId",
                "methodName": "initializeHandler"
            }, {
                "propName": "clientStyling",
                "methodName": "handleStylingChange"
            }, {
                "propName": "clientStylingUrl",
                "methodName": "handleStylingUrlChange"
            }, {
                "propName": "translationUrl",
                "methodName": "handleNewTranslations"
            }];
    }
    static get listeners() {
        return [{
                "name": "click",
                "method": "clickOutsideHandle",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "allNotificationsRead",
                "method": "resetUnseenCount",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "closePopover",
                "method": "closePopoverHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }];
    }
}
