"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 localforage_1 = require("localforage");
const external_wallet_1 = require("./wallet/external-wallet");
let walletInstance;
let communicator;
const serializeHostWallet = () => {
    const hostWallet = dataverse_kernel_1.DataverseKernel.instance.drivers.cryptoWallet.hostWallet.hostWallet;
    const hostWalletKeys = Object.keys(hostWallet);
    const serializableObject = {
        keys: hostWalletKeys,
    };
    const serializedString = JSON.stringify(serializableObject);
    localStorage.setItem("hostWalletCache", serializedString);
    // console.log("set hostWalletCache", {
    //   serializableObject,
    //   serializedString,
    // });
};
const deserializeHostWallet = () => {
    const hostWalletCache = localStorage.getItem("hostWalletCache");
    // console.log("get hostWalletCache", { hostWalletCache });
    if (hostWalletCache) {
        const { keys } = JSON.parse(hostWalletCache);
        walletInstance = new external_wallet_1.ExternalWallet();
        keys.forEach((key) => {
            dataverse_kernel_1.DataverseKernel.instance.drivers.cryptoWallet.hostWallet.hostWallet[key] =
                [{ wallet: walletInstance, isCurrent: true }];
        });
        // console.log(
        //   "hostWallet",
        //   DataverseKernel.instance.drivers.cryptoWallet.hostWallet.hostWallet,
        // );
    }
};
const versionCheck = () => {
    const METEOR_IFRAME_VERSION = localStorage.getItem("METEOR_IFRAME_VERSION");
    if (!METEOR_IFRAME_VERSION ||
        METEOR_IFRAME_VERSION !== process.env.PACKAGE_VERSION) {
        localStorage.clear();
        indexedDB.deleteDatabase("localforage");
        localStorage.setItem("METEOR_IFRAME_VERSION", process.env.PACKAGE_VERSION);
        return true;
    }
    return false;
};
class LocalStorageProvider {
    localforage = localforage_1.default.createInstance({
        driver: localforage_1.default.LOCALSTORAGE,
    });
    setItem(key, val) {
        return this.localforage.setItem(key, val);
    }
    getItem(key) {
        return this.localforage.getItem(key);
    }
    getKeys() {
        return this.localforage.keys();
    }
    removeItem(key) {
        return this.localforage.removeItem(key);
    }
    clear() {
        return this.localforage.clear();
    }
}
function injectKernel() {
    // console.log({
    //   env: process.env,
    //   DATAVERSE: process.env.DATAVERSE,
    // });
    // check version
    const clearedCache = versionCheck();
    // check if brave
    const isBrave = !!navigator.brave;
    console.log({
        isBrave,
        METEOR_IFRAME_VERSION: process.env.PACKAGE_VERSION,
        clearedCache,
    });
    if (!dataverse_kernel_1.DataverseKernel.instance) {
        dataverse_kernel_1.DataverseKernel.init(isBrave
            ? {
                localStorageProvider: new LocalStorageProvider(),
            }
            : undefined);
        // console.log("DataverseKernel init finished.");
    }
    deserializeHostWallet();
    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, event) => {
                // 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: event.origin });
                    serializeHostWallet();
                }
                else {
                    // check if connected wallet
                    const currentWallet = await dataverse_kernel_1.DataverseKernel.instance.drivers.cryptoWallet.hostWallet.getCurrentWalletByHost(event.origin);
                    if (!currentWallet) {
                        // connect wallet first
                        await dataverse_kernel_1.DataverseKernel.instance.eventListener.connectWallet({
                            walletInstance,
                        }, { origin: event.origin });
                        serializeHostWallet();
                    }
                    res = await dataverse_kernel_1.DataverseKernel.instance.eventListener[args.method](args.params, { origin: event.origin });
                }
                // console.log("Kernel => onHandleMethod => return", args);
                return res;
            },
        });
        // console.log("Communicator init finished.");
    }
    window.top?.postMessage({ type: "METEOR_IFRAME_READY" }, "*");
}
exports.injectKernel = injectKernel;
