const {
    $,
    showView,
    showFlash,
    goBack,
    clearViewStack,
    onViewLeave,
} = require("./helpers");
const { state, saveState } = require("../../shared/state");
const { decryptWithPassword } = require("../../shared/vault");
const {
    removeWalletFromState,
    broadcastActiveChanged,
} = require("../../shared/walletDelete");

let deleteWalletIndex = null;
let ctx = null;

// Drop the password from the DOM and the wallet selection from the
// closure. Registered as the view-leave handler as well as run on entry,
// so the typed password does not sit in the hidden view after the user
// navigates away by any route, including the Settings gear.
function clear() {
    deleteWalletIndex = null;
    $("delete-wallet-password").value = "";
    $("delete-wallet-flash").textContent = "";
    $("delete-wallet-flash").style.visibility = "hidden";
}

function show(walletIdx) {
    clear();
    deleteWalletIndex = walletIdx;
    const wallet = state.wallets[walletIdx];
    $("delete-wallet-name").textContent =
        wallet.name || "Wallet " + (walletIdx + 1);
    showView("delete-wallet-confirm");
}

function init(_ctx) {
    ctx = _ctx;

    onViewLeave("delete-wallet-confirm", clear);

    // No wipe here: goBack() routes through showView(), which runs the
    // leave hook.
    $("btn-delete-wallet-back").addEventListener("click", () => {
        goBack();
    });

    $("btn-delete-wallet-confirm").addEventListener("click", async () => {
        const pw = $("delete-wallet-password").value;
        if (!pw) {
            $("delete-wallet-flash").textContent =
                "Please enter your password.";
            $("delete-wallet-flash").style.visibility = "visible";
            return;
        }

        if (deleteWalletIndex === null) {
            $("delete-wallet-flash").textContent =
                "No wallet selected for deletion.";
            $("delete-wallet-flash").style.visibility = "visible";
            return;
        }

        const btn = $("btn-delete-wallet-confirm");
        btn.disabled = true;
        btn.classList.add("text-muted");

        const walletIdx = deleteWalletIndex;
        const wallet = state.wallets[walletIdx];

        // Verify password against the wallet's encrypted data
        try {
            await decryptWithPassword(wallet.encryptedSecret, pw);
        } catch (_e) {
            $("delete-wallet-flash").textContent =
                "That password is incorrect. Please try again.";
            $("delete-wallet-flash").style.visibility = "visible";
            btn.disabled = false;
            btn.classList.remove("text-muted");
            return;
        }

        // Remove the wallet and repair selection, permissions and hasWallet
        const { activeAddressChanged } = removeWalletFromState(
            state,
            walletIdx,
        );

        deleteWalletIndex = null;

        if (!state.hasWallet) {
            clearViewStack();
            await saveState();
            // Save before broadcasting: the background reads the active
            // address back out of storage to build accountsChanged.
            if (activeAddressChanged) broadcastActiveChanged();
            showView("welcome");
        } else {
            await saveState();
            if (activeAddressChanged) broadcastActiveChanged();
            // Reset stack to [main] so Settings back goes home.
            // Use require() lazily to avoid circular dependency
            // (settings.js requires deleteWallet.js).
            clearViewStack();
            state.viewStack.push("main");
            ctx.renderWalletList();
            const settings = require("./settings");
            settings.show();
            showFlash("Wallet deleted.");
        }
    });
}

module.exports = { init, show };
