// State management and extension storage persistence.

const { DEFAULT_RPC_URL, DEFAULT_BLOCKSCOUT_URL } = require("./constants");
const { networkById } = require("./networks");

const storageApi =
    typeof browser !== "undefined"
        ? browser.storage.local
        : chrome.storage.local;

const DEFAULT_STATE = {
    hasWallet: false,
    wallets: [],
    trackedTokens: [],
    networkId: "mainnet",
    rpcUrl: DEFAULT_RPC_URL,
    blockscoutUrl: DEFAULT_BLOCKSCOUT_URL,
    lastBalanceRefresh: 0,
    activeAddress: null,
    allowedSites: {},
    deniedSites: {},
    rememberSiteChoice: true,
    showZeroBalanceTokens: true,
    hideLowHolderTokens: true,
    hideFraudContracts: true,
    hideDustTransactions: true,
    dustThresholdGwei: 100000,
    utcTimestamps: false,
    fraudContracts: [],
    tokenHolderCache: {},
    theme: "system",
    debugMode: false,
};

const state = {
    ...DEFAULT_STATE,
    currentView: null,
    selectedWallet: null,
    selectedAddress: null,
    selectedToken: null,
    viewData: {},
    viewStack: [],
};

// Return the network configuration for the currently selected network.
function currentNetwork() {
    return networkById(state.networkId);
}

async function saveState() {
    const persisted = {
        hasWallet: state.hasWallet,
        wallets: state.wallets,
        trackedTokens: state.trackedTokens,
        networkId: state.networkId,
        rpcUrl: state.rpcUrl,
        blockscoutUrl: state.blockscoutUrl,
        lastBalanceRefresh: state.lastBalanceRefresh,
        activeAddress: state.activeAddress,
        allowedSites: state.allowedSites,
        deniedSites: state.deniedSites,
        rememberSiteChoice: state.rememberSiteChoice,
        showZeroBalanceTokens: state.showZeroBalanceTokens,
        hideLowHolderTokens: state.hideLowHolderTokens,
        hideFraudContracts: state.hideFraudContracts,
        hideDustTransactions: state.hideDustTransactions,
        dustThresholdGwei: state.dustThresholdGwei,
        utcTimestamps: state.utcTimestamps,
        fraudContracts: state.fraudContracts,
        tokenHolderCache: state.tokenHolderCache,
        theme: state.theme,
        debugMode: state.debugMode,
        currentView: state.currentView,
        selectedWallet: state.selectedWallet,
        selectedAddress: state.selectedAddress,
        selectedToken: state.selectedToken,
        viewData: state.viewData,
        viewStack: state.viewStack,
    };
    await storageApi.set({ autistmask: persisted });
}

async function loadState() {
    const result = await storageApi.get("autistmask");
    if (result.autistmask) {
        const saved = result.autistmask;
        state.wallets = saved.wallets || [];
        // Derived, never read from storage: a profile persisted with the flag
        // out of step with the wallet list would otherwise stay broken on
        // every load. Nothing depends on the two disagreeing.
        state.hasWallet = state.wallets.length > 0;
        state.trackedTokens = saved.trackedTokens || [];
        state.networkId = saved.networkId || DEFAULT_STATE.networkId;
        state.rpcUrl = saved.rpcUrl || DEFAULT_STATE.rpcUrl;
        state.blockscoutUrl =
            saved.blockscoutUrl || DEFAULT_STATE.blockscoutUrl;
        state.lastBalanceRefresh = saved.lastBalanceRefresh || 0;
        state.activeAddress = saved.activeAddress || null;
        state.allowedSites =
            saved.allowedSites && !Array.isArray(saved.allowedSites)
                ? saved.allowedSites
                : {};
        state.deniedSites =
            saved.deniedSites && !Array.isArray(saved.deniedSites)
                ? saved.deniedSites
                : {};
        state.rememberSiteChoice =
            saved.rememberSiteChoice !== undefined
                ? saved.rememberSiteChoice
                : true;
        state.showZeroBalanceTokens =
            saved.showZeroBalanceTokens !== undefined
                ? saved.showZeroBalanceTokens
                : true;
        state.hideLowHolderTokens =
            saved.hideLowHolderTokens !== undefined
                ? saved.hideLowHolderTokens
                : true;
        state.hideFraudContracts =
            saved.hideFraudContracts !== undefined
                ? saved.hideFraudContracts
                : true;
        state.hideDustTransactions =
            saved.hideDustTransactions !== undefined
                ? saved.hideDustTransactions
                : true;
        state.dustThresholdGwei =
            saved.dustThresholdGwei !== undefined
                ? saved.dustThresholdGwei
                : 100000;
        state.utcTimestamps =
            saved.utcTimestamps !== undefined ? saved.utcTimestamps : false;
        state.fraudContracts = saved.fraudContracts || [];
        state.tokenHolderCache = saved.tokenHolderCache || {};
        state.theme = saved.theme || "system";
        state.debugMode =
            saved.debugMode !== undefined ? saved.debugMode : false;
        state.currentView = saved.currentView || null;
        state.selectedWallet =
            saved.selectedWallet !== undefined ? saved.selectedWallet : null;
        state.selectedAddress =
            saved.selectedAddress !== undefined ? saved.selectedAddress : null;
        state.selectedToken = saved.selectedToken || null;
        state.viewData = saved.viewData || {};
        state.viewStack = Array.isArray(saved.viewStack) ? saved.viewStack : [];
    }
}

function currentAddress() {
    if (state.selectedWallet === null || state.selectedAddress === null) {
        return null;
    }
    return state.wallets[state.selectedWallet].addresses[state.selectedAddress];
}

module.exports = {
    state,
    saveState,
    loadState,
    currentAddress,
    currentNetwork,
};
