const actionName = "getDPEData";

const commonPostMessage = function (messageObj) {
    const obj = { ...messageObj, urlParams: window.location.search, origin: "template" }
    window.parent.postMessage(obj, '*');
};

export const getDPEData = async function () {
    return new Promise((resolve, reject) => {
        let processed = false;
        let timeoutId = setTimeout(() => {
            if (!processed) {
                window.removeEventListener("message", eventCallback);
                reject("timeout")
            }
        }, 5000);

        const eventCallback = (e) => {
            if(e.data.action !== actionName) {
                return;
            }
            processed = true;
            window.removeEventListener("message", eventCallback);
            clearTimeout(timeoutId);
            try {
                const data = JSON.parse(e.data.data);
                resolve(data.data)
            } catch (error) {
                console.error("Error parsing DPE data", error);
                resolve(null)
            }
        }
        commonPostMessage({ action: actionName, data: window.location.search }); 
        window.addEventListener("message", eventCallback)
    })
}