/**
 * main.js
 *
 * Bootstraps Vuetify and other plugins then mounts the App`
 */

// Components
import App from './App.vue'

// Composables
import { createApp } from 'vue'

// Plugins
import { registerPlugins } from '@/plugins'
import '@/styles/style.scss'
import "./socketInit.js"
import "./version.js"
import { web3modal } from '@/blockchain/web3modal.js'
import { BrowserProvider } from 'ethers'
import { setProvider } from '@/blockchain/provider.js'
import { updateAccounts } from '@/blockchain/wallet.js'
import { useWalletStore } from '@/blockchain/wallet.js'

BigInt.prototype.toJSON = function() { return this.toString() }

const app = createApp(App)
registerPlugins(app)
app.mount('#app')
window.$vuetify = app

// Check if Web3Modal has an existing connection on app start
web3modal.subscribeProvider(async (state) => {
    if (state.isConnected && state.provider) {
        try {
            console.log('Restoring existing Web3Modal connection')
            const p = new BrowserProvider(state.provider)
            setProvider(p)

            const network = await p.getNetwork()
            const chainId = Number(network.chainId)

            const ws = useWalletStore()
            ws.chainId = chainId

            await updateAccounts(chainId, p)
        } catch (e) {
            console.log('Error restoring connection', e)
        }
    }
})
