"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectKernel = void 0;
const dataverse_kernel_1 = require("@dataverse/dataverse-kernel");
const communicator_1 = require("@meteor-web3/communicator");
const external_wallet_1 = require("./wallet/external-wallet");
let walletInstance;
let communicator;
function injectKernel() {
    // console.log({
    //   env: process.env,
    //   DATAVERSE: process.env.DATAVERSE,
    // });
    if (!dataverse_kernel_1.DataverseKernel.instance) {
        dataverse_kernel_1.DataverseKernel.init();
        // console.log("DataverseKernel init finished.");
    }
    if (!walletInstance) {
        walletInstance = new external_wallet_1.ExternalWallet();
        // console.log("ExternalWallet init finished.");
    }
    if (!communicator) {
        communicator = new communicator_1.Communicator({
            source: window,
            target: window.top,
            runningEnv: "Kernel",
            methodHandler: async (args) => {
                // console.log("Kernel => onHandleMethod", args);
                let res;
                if (args.method === "connectWallet") {
                    // only ExternalWallet is supported in Iframe
                    res = await dataverse_kernel_1.DataverseKernel.instance.eventListener.connectWallet({
                        ...args.params,
                        walletInstance,
                    }, { origin });
                }
                else {
                    // check if connected wallet
                    const currentWallet = await dataverse_kernel_1.DataverseKernel.instance.drivers.cryptoWallet.hostWallet.getCurrentWalletByHost(origin);
                    if (!currentWallet) {
                        // connect wallet first
                        await dataverse_kernel_1.DataverseKernel.instance.eventListener.connectWallet({
                            walletInstance,
                        }, { origin });
                    }
                    res = await dataverse_kernel_1.DataverseKernel.instance.eventListener[args.method](args.params, { origin });
                }
                // console.log("Kernel => onHandleMethod => return", args);
                return res;
            },
        });
        // console.log("Communicator init finished.");
    }
}
exports.injectKernel = injectKernel;
