"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("../util");
exports.createAsyncGetProxy = function (onGet) {
    var proxy = new Proxy({}, {
        get: function (_, propertyKey) { return function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return onGet(propertyKey, args);
        }; },
    });
    return proxy;
};
exports.sendMessagePasserMessage = function (target, propertyKey, params) {
    var identifier = util_1.generateId();
    return new Promise(function (resolve, reject) {
        var onMessage = function (_a) {
            var _b = _a.data, data = _b.data, resIdentifier = _b.identifier, error = _b.error;
            if (identifier !== resIdentifier) {
                return;
            }
            target.removeEventListener("message", onMessage);
            if (error !== undefined) {
                return reject(Object.assign(new Error(), error));
            }
            resolve(data);
        };
        target.addEventListener("message", onMessage);
        var request = {
            identifier: identifier,
            method: propertyKey,
            params: params,
        };
        target.postMessage(request);
    });
};
exports.createMessagePasserClient = function (target) {
    var sendMessage = function (propertyKey, params) {
        return exports.sendMessagePasserMessage(target, propertyKey, params);
    };
    return exports.createAsyncGetProxy(sendMessage);
};
