"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SYSTEM_EXTENSION_ID = void 0;
exports.getExtensionElement = getExtensionElement;
exports.isExtensionInstalled = isExtensionInstalled;
exports.dispatchExtensionEvent = dispatchExtensionEvent;
exports.postMessage = postMessage;
exports.postCallMessage = postCallMessage;
exports.callExtensionMethod = callExtensionMethod;
exports.setup = setup;
const STRING_1 = require("../../constant/STRING");
const id_1 = require("../../util/id");
const _callback = {};
exports.SYSTEM_EXTENSION_ID = '___SYSTEM__EXTENSION___';
function getExtensionElement() {
    return document.getElementById(exports.SYSTEM_EXTENSION_ID);
}
function isExtensionInstalled() {
    const installed = !!getExtensionElement();
    return installed;
}
function dispatchExtensionEvent(type, id, data) {
    const element = getExtensionElement();
    element.dispatchEvent(new CustomEvent('message', {
        detail: { type, id, data },
    }));
}
function postMessage(data, callback) {
    setup();
    const installed = isExtensionInstalled();
    if (installed) {
        const id = (0, id_1.uuid)();
        _callback[id] = callback;
        dispatchExtensionEvent('send', id, data);
    }
    else {
        callback(undefined, 'extension not installed');
    }
}
function postCallMessage(data, callback) {
    postMessage({
        type: STRING_1.CALL,
        data,
    }, callback);
}
function callExtensionMethod(type, method, data, callback) {
    postCallMessage({
        type,
        method,
        data,
    }, callback);
}
let _init = false;
function setup() {
    if (_init) {
        return;
    }
    const element = getExtensionElement();
    element.addEventListener('message', (event) => {
        const { detail } = event;
        const { type, id, data } = detail;
        if (type === STRING_1.CALLBACK) {
            const callback = _callback[id];
            if (callback) {
                delete _callback[id];
                callback(data);
            }
        }
    });
    _init = true;
}
//# sourceMappingURL=index.js.map