import { DataverseKernel } from "@dataverse/dataverse-kernel";
import { IframeCommunicator } from "@meteor-web3/communicator";
import { ExternalWallet } from "./crypto-wallet/external-wallet";
let walletInstance;
let communicator;
export function injectKernel() {
    console.log({
        env: process.env,
        DATAVERSE: process.env.DATAVERSE,
    });
    if (!DataverseKernel.instance) {
        DataverseKernel.init();
        console.log("DataverseKernel init finished.");
    }
    if (!walletInstance) {
        walletInstance = new ExternalWallet();
        console.log("ExternalWallet init finished.");
    }
    if (!communicator) {
        communicator = new IframeCommunicator({
            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 DataverseKernel.instance.eventListener.connectWallet({
                        ...args.params,
                        walletInstance,
                    }, { origin });
                }
                else {
                    // check if connected wallet
                    const currentWallet = await DataverseKernel.instance.drivers.cryptoWallet.hostWallet.getCurrentWalletByHost(origin);
                    if (!currentWallet) {
                        // connect wallet first
                        await DataverseKernel.instance.eventListener.connectWallet({
                            walletInstance,
                        }, { origin });
                    }
                    res = await DataverseKernel.instance.eventListener[args.method](args.params, { origin });
                }
                console.log("Kernel => onHandleMethod => return", args);
                return res;
            },
        });
        console.log("Communicator init finished.");
    }
}
