"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setup = exports.callMethod = exports.postCallMessage = exports.postMessage = void 0;
const id_1 = require("../../util/id");
const isInstalled = () => {
    const __EXTENSION_INSTALLED = !!document.getElementById('__EXTENSION_INSTALLED');
    return __EXTENSION_INSTALLED;
};
const _callback = {};
function postMessage(data, callback) {
    setup();
    const installed = isInstalled();
    if (installed) {
        const id = (0, id_1.uuid)();
        _callback[id] = callback;
        window.postMessage({ type: 'EXTENSION_IN', id, data }, location.origin);
    }
    else {
        callback(undefined, 'extension not installed');
    }
}
exports.postMessage = postMessage;
function postCallMessage(data, callback) {
    postMessage({
        type: 'CALL',
        data,
    }, callback);
}
exports.postCallMessage = postCallMessage;
function callMethod(type, method, data, callback) {
    postCallMessage({
        type,
        method,
        data,
    }, callback);
}
exports.callMethod = callMethod;
let _init = false;
function setup() {
    if (_init) {
        return;
    }
    window.addEventListener('message', (event) => {
        // only accept messages from this window
        if (event.source !== window) {
            return;
        }
        const { data } = event;
        const { type, id, data: _data } = data;
        if (type && type === 'EXTENSION_OUT' && id) {
            const callback = _callback[id];
            if (callback) {
                delete _callback[id];
                callback(_data);
            }
        }
    });
    _init = true;
}
exports.setup = setup;
//# sourceMappingURL=index.js.map