import {Exchange} from "@/blockchain/orderlib.js";
import {useOrderStore, useStore} from "@/store/store.js";
import {queryHelperContract} from "@/blockchain/contract.js";
import {SingletonCoroutine} from "@/misc.js";

import {provider} from "@/blockchain/provider.js";


export async function findRoute(helper, chainId, tokenA, tokenB) {
    console.log('getting raw routes', helper, tokenA.a, tokenB.a)
    const rawRoutes = await helper.getRoutes(tokenA.a, tokenB.a)
    // todo expose all available pools
    console.log('raw routes', rawRoutes)
    let result = null // we actually only find a single pool for now
    for (let [exchange, fee, pool] of rawRoutes) {
        exchange = Number(exchange)
        fee = Number(fee)
        if (!result || result.fee > fee) {
            switch (exchange) {
                case 0: // UniswapV2
                    throw Error('Uniswap V2 not yet supported')
                case 1: // UniswapV3
                    const inverted = tokenA.a < tokenB.a;
                    const [token0, token1] = inverted ? [tokenA, tokenB] : [tokenB, tokenA]
                    result = {chainId, exchange: Exchange.UniswapV3, pool, fee, token0, token1, inverted}
                    break
            }
        }
    }
    return result ? [result] : []
}

async function componentFindRoute() {
    const s = useStore()
    const os = useOrderStore()
    const tokenA = os.tokenA
    const tokenB = os.tokenB
    os.routes = []
    if (!tokenA || !tokenB)
        return
    console.log('finding route', s.chainId, tokenA, tokenB)
    os.routesPending = true
    try {
        console.log('getting query helper')
        const helper = await queryHelperContract(s.helper, provider)
        if (!helper) {
            console.log('no helper')
        } else {
            const result = await findRoute(helper, s.chainId, tokenA, tokenB)
            console.log('found route', result)
            os.routes = result
        }
    } catch (e) {
        // console.log('ignoring routes exception', e)
    } finally {
        os.routesPending = false
    }
}

export const routeFinder = new SingletonCoroutine(componentFindRoute, 10)
