/** @odoo-module **/
import { Markup } from "@odoo/owl";
import { browser } from "@web/core/browser/browser";
import { registry } from "@web/core/registry";

export const webNotificationService = {
    dependencies: ["bus_service", "notification"],
    start(env, { bus_service, notification }) {
        let webNotifTimeouts = {};
        /**
         * Displays the web notification on the user's screen
         */
        async function displaywebNotification(notifications) {
            // Clear existing timeouts
            Object.values(webNotifTimeouts).forEach((notif) =>
                browser.clearTimeout(notif)
            );
            webNotifTimeouts = {};
            for (const notif of notifications) {
                // Using async/await to ensure asynchronous operations complete before moving on
                await new Promise(resolve =>
                    browser.setTimeout(function () {
                        notification.add(notif.message, {
                            title: notif.title,
                            type: notif.type,
                            sticky: notif.sticky,
                            className: notif.className,
                        });
                        resolve();
                    })
                );
            }
        }
        bus_service.addEventListener("notification", ({ detail: notifications }) => {
            for (const { payload, type } of notifications) {
                if (type === "web.notify") {
                    displaywebNotification(payload);
                }
            }
        });
        bus_service.start();
    },
};
registry.category("services").add("webNotification", webNotificationService);
