import { logger } from "../../utils";

function getCmp () {

    //if __cmp exists, return it and we are done
    if(window.__cmp) return window.__cmp;
    const ERROR_MSG = "__cmp not found";
    //if __cmp doesn't exist, perhaps we are in an iFrame
    //the __cmp should create an iFrame called __cmpLocator so
    //check each parent up to the top level to find that iFrame
    var f = window;
    //if we aren't in an iframe we don't want to make a stub
    if(f === window.top) {
        logger.error(ERROR_MSG);
        return;
    }
    var cmpFrame;
    while (!cmpFrame) {
        f = f.parent;
        try {
            if (f.frames["__cmpLocator"]) cmpFrame = f;
        } catch (e) {//empty
        }
        if (f === window.top) break;
    }

    //if we can't find the cmpLocator frame, don't make the stub
    if (!cmpFrame) {
        logger.error(ERROR_MSG);
        return;
    }

    //If the cmp locator is found in a parent frame, we make
    //a __cmp stub that posts messages to the frame containing
    //the real cmp and listens for responses
    var cmpCallbacks = {};

    window.__cmp = function (cmd, arg, callback) {
        var callId = Math.random() + "";
        var msg = {
            __cmpCall: {
                command: cmd,
                parameter: arg,
                callId: callId
            }
        };
        cmpCallbacks[callId] = callback;
        cmpFrame.postMessage(msg, "*");
    };

    window.addEventListener("message", function (event) {
        var json = event.data;
        if (typeof json === "string") {
            try {
                json = JSON.parse(event.data);
            } catch (e) {//empty
            }
        }

        if (json.__cmpReturn) {
            var i = json.__cmpReturn;
            if (cmpCallbacks[i.callId]) {
                cmpCallbacks[i.callId](i.returnValue, i.success);
                delete cmpCallbacks[i.callId];
            }
        }
    }, false);

    return window.__cmp;
}

export default getCmp;
