import { h } from "@stencil/core";
import { translate, getTranslations } from "../../utils/locale.utils";
import { deleteAll, getNotifications, markAllAsRead } from "../../api/methods";
import { CloseCircleOutlined, LoadingOutlined } from "@ant-design/icons-svg";
import { renderIconDefinitionToSVGElement } from "@ant-design/icons-svg/es/helpers";
import { notificationCache } from "../../cache";
export class NutsPopover {
    constructor() {
        this.currentPage = 0;
        this.nextPage = async () => {
            this.currentPage++;
            this.triggerGetNotifications();
        };
        this.prevPage = async () => {
            if (this.currentPage > 0) {
                this.currentPage--;
                this.triggerGetNotifications();
            }
        };
        this.setClientStyling = () => {
            let sheet = document.createElement('style');
            sheet.innerHTML = this.clientStyling;
            this.stylingContainer.prepend(sheet);
        };
        this.setClientStylingURL = () => {
            let url = new URL(this.clientStylingUrl);
            let cssFile = document.createElement('style');
            fetch(url.href)
                .then((res) => res.text())
                .then((data) => {
                cssFile.innerHTML = data;
                setTimeout(() => {
                    this.stylingContainer.prepend(cssFile);
                }, 1);
            })
                .catch((err) => {
                console.log('error ', err);
            });
        };
        this.markAllNotificationsAsRead = async () => {
            const markedAllNotificationsAsRead = await markAllAsRead({
                baseUrl: this.baseUrl,
                token: this.token
            });
            if (markedAllNotificationsAsRead) {
                this.allNotificationsRead.emit();
                this.unseenCount = 0;
                notificationCache.markAllAsRead();
            }
        };
        this.deleteAllNotifications = async () => {
            const allNotificationsDeleted = await deleteAll({
                baseUrl: this.baseUrl,
                token: this.token
            });
            if (allNotificationsDeleted) {
                this.allMessagesDeteled.emit();
                this.unseenCount = 0;
                this.currentPage = 0;
                notificationCache.clearAll();
                this.showDeleteAllPopup = false;
            }
        };
        this.closePopover = () => {
            this.closePopoverEmmiter.emit();
        };
        this.showDeletePopup = () => {
            var _a;
            if (((_a = this.notifications) === null || _a === void 0 ? void 0 : _a.length) === 0) {
                return;
            }
            this.showDeleteAllPopup = !this.showDeleteAllPopup;
        };
        this.assignRefToStylingContainer = (ref) => {
            this.stylingContainer = ref;
        };
        this.language = undefined;
        this.userId = undefined;
        this.operatorId = undefined;
        this.token = undefined;
        this.sessionId = undefined;
        this.backendUrl = undefined;
        this.unseenCount = undefined;
        this.clientStylingUrl = undefined;
        this.notificationAction = undefined;
        this.clientStyling = '';
        this.translationUrl = '';
        this.notifications = undefined;
        this.isLoading = false;
        this.isNotificationsLoading = true;
        this.showMarkAll = false;
        this.limitStylingAppends = false;
        this.showDeleteAllPopup = false;
        this.hasMore = true;
    }
    messageDeletedHandler(event) {
        notificationCache.deleteById(event.detail);
    }
    messageReadHandler(event) {
        const { messageId, mark } = event.detail;
        notificationCache.markAsRead(messageId, mark);
    }
    clickOutsideHandle(ev) {
        var _a;
        const target = ev.target;
        if (this.showDeleteAllPopup && this.dropdownRef && !((_a = this.dropdownRef) === null || _a === void 0 ? void 0 : _a.contains(target))) {
            this.showDeleteAllPopup = false;
        }
    }
    unseenCountHandler(newValue) {
        if (newValue == 0) {
            this.showMarkAll = false;
        }
        else {
            this.showMarkAll = true;
        }
    }
    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() {
        // start custom styling area
        if (!this.limitStylingAppends && this.stylingContainer) {
            if (this.clientStyling)
                this.setClientStyling();
            if (this.clientStylingUrl)
                this.setClientStylingURL();
            this.limitStylingAppends = true;
        }
        // end custom styling area
    }
    async triggerGetNotifications() {
        this.isNotificationsLoading = true;
        try {
            await notificationCache.loadPageFromApi(this.currentPage, async () => getNotifications({
                baseUrl: this.baseUrl,
                token: this.token,
                page: this.currentPage
            }));
        }
        finally {
            this.isNotificationsLoading = false;
        }
    }
    connectedCallback() {
        this.baseUrl = `${this.backendUrl}/v1/${this.operatorId}`;
        notificationCache.observePageUpdate((notifications, hasMore) => {
            if ((notifications === null || notifications === void 0 ? void 0 : notifications.length) === 0 && this.currentPage > 0) {
                // if it's last notification on it's page go back a page and retrigger
                this.currentPage--;
                this.triggerGetNotifications();
                return;
            }
            this.notifications = notifications;
            this.hasMore = hasMore;
        });
        this.triggerGetNotifications();
        if (this.unseenCount != 0) {
            this.showMarkAll = true;
        }
    }
    render() {
        var _a, _b;
        return (h("div", { key: 'f1e94beefef26d3934955020552014a30b0544ed', class: "Popover", ref: this.assignRefToStylingContainer }, h("div", { key: '7cf55accedb0b20be815f8755ae8b9f316ce2416', class: "Header" }, h("div", { key: '11092950fc491f1b6e8ee60ae23703f9981ec2fa', class: "Title" }, translate('notifications', this.language), this.unseenCount > 0 ? h("div", { class: "UnseenCounter" }, this.unseenCount) : ''), this.showMarkAll && (h("div", { key: '8d041cdbc51818c8a5119569dd919c6ab5daa0c0', class: "MarkAsRead", onClick: this.markAllNotificationsAsRead }, translate('markAllAsRead', this.language))), h("div", { key: 'b8865c62341b0fc4db24741cb46bd0edc308a935', class: "ActionButtons" }, h("button", { key: 'a074740e1641941d35b9facf1796371da126530f', class: `DeleteAll${this.showDeleteAllPopup ? ' Active' : ''}`, onClick: this.showDeletePopup, disabled: !((_a = this.notifications) === null || _a === void 0 ? void 0 : _a.length) }, h("svg", { key: 'a543450f4ff6261d140a26ca5a97b988389ff982', width: "16", height: "16", viewBox: "0 0 20 20", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h("path", { key: '0eed6954821bea3d392b21446894fd5651fb1674', d: "M4.375 15.4375C4.375 16.1758 4.94922 16.75 5.6875 16.75H13.5625C14.2734 16.75 14.875 16.1758 14.875 15.4375V6.25H4.375V15.4375ZM11.8125 8.4375C11.8125 8.21875 12.0039 8 12.25 8C12.4688 8 12.6875 8.21875 12.6875 8.4375V14.5625C12.6875 14.8086 12.4688 15 12.25 15C12.0039 15 11.8125 14.8086 11.8125 14.5625V8.4375ZM9.1875 8.4375C9.1875 8.21875 9.37891 8 9.625 8C9.84375 8 10.0625 8.21875 10.0625 8.4375V14.5625C10.0625 14.8086 9.84375 15 9.625 15C9.37891 15 9.1875 14.8086 9.1875 14.5625V8.4375ZM6.5625 8.4375C6.5625 8.21875 6.75391 8 7 8C7.21875 8 7.4375 8.21875 7.4375 8.4375V14.5625C7.4375 14.8086 7.21875 15 7 15C6.75391 15 6.5625 14.8086 6.5625 14.5625V8.4375ZM15.3125 3.625H12.25L11.9219 2.99609C11.8398 2.85938 11.7031 2.75 11.5391 2.75H7.68359C7.51953 2.75 7.38281 2.85938 7.30078 2.99609L7 3.625H3.9375C3.69141 3.625 3.5 3.84375 3.5 4.0625V4.9375C3.5 5.18359 3.69141 5.375 3.9375 5.375H15.3125C15.5312 5.375 15.75 5.18359 15.75 4.9375V4.0625C15.75 3.84375 15.5312 3.625 15.3125 3.625Z", fill: "currentColor" }))), h("button", { key: 'f79e2a36a88b8b29c542ecb631d401258fbc606b', class: "ClosePopover", onClick: this.closePopover }, h("div", { key: '06ca6ddd2d1c402f05cdb74986c85c50780ee829', innerHTML: renderIconDefinitionToSVGElement(CloseCircleOutlined, {
                extraSVGAttrs: { width: '20px', height: '20px', fill: '#A1A1B2' }
            }) }))), this.showDeleteAllPopup && (h("div", { key: '0185c7fba8fbd79ebba6247e01a7ce85652b755f', class: "DeleteAllDropdown", ref: (el) => (this.dropdownRef = el) }, h("button", { key: 'f183425b99dcb14758eea42e165ec628fb97a421', onClick: this.deleteAllNotifications }, translate('deleteAllMessages', this.language))))), !this.isLoading && (h("div", { key: 'ff6474f5107c9cd28cf61eaf8db3fe06cfe51fae', class: "NotificationList" }, this.isNotificationsLoading ? (h("div", { class: "Loading", innerHTML: renderIconDefinitionToSVGElement(LoadingOutlined, {
                extraSVGAttrs: { width: '30px', height: '30px', fill: '#A1A1B2' }
            }) })) : ((_b = this.notifications) === null || _b === void 0 ? void 0 : _b.length) > 0 ? (this.notifications.map((item) => {
            var _a;
            return (h("nuts-notification", { "client-styling": this.clientStyling, "client-styling-url": this.clientStylingUrl, key: item.id, "user-id": this.userId, "operator-id": this.operatorId, content: item.content, "message-id": item.id, badge: ((_a = item.actor) === null || _a === void 0 ? void 0 : _a.data) || '', sessionId: this.sessionId, date: item.createdAt, read: item.read, seen: item.seen, language: this.language, "notification-action": this.notificationAction, token: this.token, "backend-url": this.backendUrl, "redirect-url": item.cta.data.url, "translation-url": this.translationUrl, "max-text-length": 200, "max-lines": 5 }));
        })) : (h("div", { class: "NoMessages" }, h("svg", { width: "120", height: "108", viewBox: "0 0 120 108", fill: "none" }, h("circle", { cx: "11.3191", cy: "30.7872", r: "6.31915", stroke: "#3D3D4D", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("ellipse", { cx: "60.117", cy: "27.9787", rx: "5.96809", ry: "5.61702", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("path", { d: "M79.5424 49.4934C79.5424 44.1598 77.6437 39.0446 74.2641 35.2732C70.8844 31.5017 66.3006 29.3829 61.5211 29.3829C56.7415 29.3829 52.1578 31.5017 48.7781 35.2732C45.3985 39.0446 43.4998 44.1598 43.4998 49.4934C43.4998 72.9557 34.4892 79.6592 34.4892 79.6592H88.553C88.553 79.6592 79.5424 72.9557 79.5424 49.4934Z", fill: "#292933" }), h("path", { d: "M68.8995 81.7552C68.1496 83.551 67.0731 85.0417 65.778 86.0779C64.4828 87.1141 63.0144 87.6595 61.5198 87.6595C60.0252 87.6595 58.5568 87.1141 57.2617 86.0779C55.9665 85.0417 54.8901 83.551 54.1401 81.7552", fill: "#292933" }), h("path", { d: "M81.2976 50.2203C81.2976 68.2545 87.2222 76.7327 90.2814 79.9083C90.7671 80.4126 90.3802 81.4764 89.68 81.4764C88.0927 81.4764 86.5488 81.4764 85.0422 81.4764M68.5814 82.946C67.6854 84.8068 66.3993 86.3513 64.8518 87.425C63.3044 88.4987 61.5499 89.0638 59.7641 89.0638C57.9783 89.0638 56.2239 88.4987 54.6765 87.425C53.129 86.3513 51.8429 84.8068 50.9468 82.946M79.712 42.3723C78.6394 39.8192 77.0439 37.4727 74.991 35.4861C70.953 31.5783 65.4763 29.3829 59.7656 29.3829C54.055 29.3829 48.5783 31.5783 44.5403 35.4861C43.3681 36.6205 42.345 37.8722 41.4832 39.2127C40.4958 40.7487 39.7202 42.4013 39.1747 44.1276C38.5563 46.0847 38.2337 48.1364 38.2337 50.2203C38.2337 53.2503 38.0665 56.0106 37.7737 58.5212M34.8401 70.7608C32.9874 75.4551 30.7688 78.331 29.2526 79.9055C28.767 80.4099 29.155 81.4764 29.8551 81.4764C47.1962 81.4764 59.3571 81.4764 74.1593 81.4764", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("path", { d: "M55.6345 59.0737C55.1665 59.7144 54.4949 60.2462 53.6868 60.6159C52.8787 60.9855 51.9625 61.1801 51.0299 61.1801C50.0973 61.1801 49.1811 60.9855 48.373 60.6159C47.5649 60.2462 46.8933 59.7144 46.4254 59.0737", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("path", { d: "M73.1877 59.0737C72.7197 59.7144 72.0481 60.2462 71.24 60.6159C70.4319 60.9855 69.5157 61.1801 68.5831 61.1801C67.6506 61.1801 66.7344 60.9855 65.9263 60.6159C65.1182 60.2462 64.4465 59.7144 63.9786 59.0737", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("circle", { cx: "107.511", cy: "56.0638", r: "7.02128", stroke: "#3D3D4D", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("circle", { cx: "16.4252", cy: "58.1703", r: "4.21277", fill: "#3D3D4D" }), h("ellipse", { cx: "59.9573", cy: "104.511", rx: "25.2766", ry: "2.80851", fill: "#3D3D4D" }), h("path", { d: "M81.5317 18.1489H88.553L81.5317 25.1702H88.553", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), h("path", { d: "M96.6807 2H106.51L96.6807 11.8298H106.51", stroke: "#828299", "stroke-width": "3.5", "stroke-linecap": "round", "stroke-linejoin": "round" })), h("p", null, translate('noMessages', this.language)))))), !this.isLoading && (h("div", { key: 'ac051bc217b20856ee2fbb05c164740a2ce15034', class: "Pagination" }, h("div", { key: '4103c2541b1534674f4a395782b57cb7f412e635', class: "Button" }, h("button", { key: 'b5ea8a82ad305692ba6b7e27de3156df8755b41a', disabled: this.isNotificationsLoading || this.currentPage <= 0, onClick: this.prevPage }, h("svg", { key: '84a373abf56f161f2f566c617c2227d713bfbad5', class: "svg-icon", viewBox: "0 0 20 20" }, h("path", { key: 'a8c8e4d65eb525f98db3a9f3770c64a4cff44b0e', d: "M8.388,10.049l4.76-4.873c0.303-0.31,0.297-0.804-0.012-1.105c-0.309-0.304-0.803-0.293-1.105,0.012L6.726,9.516c-0.303,0.31-0.296,0.805,0.012,1.105l5.433,5.307c0.152,0.148,0.35,0.223,0.547,0.223c0.203,0,0.406-0.08,0.559-0.236c0.303-0.309,0.295-0.803-0.012-1.104L8.388,10.049z" })), translate('prev', this.language))), h("div", { key: '20b18543fe251fe1f2b67e002fa07ec9be8146e7', class: "Button" }, h("button", { key: '797168392bd58e443953ccac835e33660956ea27', disabled: this.isNotificationsLoading || !this.hasMore, onClick: this.nextPage }, translate('next', this.language), h("svg", { key: '3602fbc69f946074355405ec83075069bb3787c1', class: "svg-icon", viewBox: "0 0 20 20" }, h("path", { key: '679cc4531c96fe91bbdc027acfee1eb71240495d', d: "M11.611,10.049l-4.76-4.873c-0.303-0.31-0.297-0.804,0.012-1.105c0.309-0.304,0.803-0.293,1.105,0.012l5.306,5.433c0.304,0.31,0.296,0.805-0.012,1.105L7.83,15.928c-0.152,0.148-0.35,0.223-0.547,0.223c-0.203,0-0.406-0.08-0.559-0.236c-0.303-0.309-0.295-0.803,0.012-1.104L11.611,10.049z" }))))))));
    }
    static get is() { return "nuts-popover"; }
    static get originalStyleUrls() {
        return {
            "$": ["nuts-popover.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["nuts-popover.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Language code of the content"
                },
                "attribute": "language",
                "reflect": true
            },
            "userId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Unique ID of the user receiving notifications"
                },
                "attribute": "user-id",
                "reflect": true
            },
            "operatorId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Unique ID of the operator domain"
                },
                "attribute": "operator-id",
                "reflect": true
            },
            "token": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Token used to authenticate notification transactions"
                },
                "attribute": "token",
                "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
            },
            "backendUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Endpoint used for notification transactions"
                },
                "attribute": "backend-url",
                "reflect": true
            },
            "unseenCount": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The count of unseen notifications"
                },
                "attribute": "unseen-count",
                "reflect": true
            },
            "clientStylingUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Custom styling URL"
                },
                "attribute": "client-styling-url",
                "reflect": true
            },
            "notificationAction": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Decides the behaviour of the notification onClick"
                },
                "attribute": "notification-action",
                "reflect": true
            },
            "clientStyling": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Custom styling string"
                },
                "attribute": "client-styling",
                "reflect": true,
                "defaultValue": "''"
            },
            "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 {
            "notifications": {},
            "isLoading": {},
            "isNotificationsLoading": {},
            "showMarkAll": {},
            "limitStylingAppends": {},
            "showDeleteAllPopup": {},
            "hasMore": {}
        };
    }
    static get events() {
        return [{
                "method": "allNotificationsRead",
                "name": "allNotificationsRead",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "allMessagesDeteled",
                "name": "allMessagesDeleted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "closePopoverEmmiter",
                "name": "closePopover",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "unseenCount",
                "methodName": "unseenCountHandler"
            }, {
                "propName": "clientStyling",
                "methodName": "handleStylingChange"
            }, {
                "propName": "clientStylingUrl",
                "methodName": "handleStylingUrlChange"
            }, {
                "propName": "translationUrl",
                "methodName": "handleNewTranslations"
            }];
    }
    static get listeners() {
        return [{
                "name": "messageDeleted",
                "method": "messageDeletedHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "messageRead",
                "method": "messageReadHandler",
                "target": "window",
                "capture": false,
                "passive": false
            }, {
                "name": "click",
                "method": "clickOutsideHandle",
                "target": "window",
                "capture": false,
                "passive": false
            }];
    }
}
