import {useChartOrderStore} from "@/orderbuild.js";
import {changeIntervalSecs, onChartReady, setSymbol, widget} from "@/charts/chart.js";
import {usePrefStore, useStore} from "@/store/store.js";
import {lookupSymbol} from "@/charts/datafeed.js";
import {track} from "@/track.js";

import {socket} from "@/socket.js";

export async function getShareUrl() {
    const co = useChartOrderStore();
    const s = useStore()
    const sym = co.selectedSymbol
    console.log('symbol', sym)
    const data = {
        version: 1,
        chainId: s.chainId,
        orders: co.orders,
        symbol: {
            base: {a: sym.base.a, s: sym.base.s},
            quote: {a: sym.quote.a, s: sym.quote.s},
            route: {
                fee: sym.fee,
                exchange: sym.exchangeId,
            }
        },
        period: co.intervalSecs,
    }
    const json = JSON.stringify(data)
    console.log('sharing data', json, data)
    const snapshot = await takeSnapshot()

    const code = await new Promise((resolve)=>socket.emit('share', data, snapshot, resolve))
    if (code===null) return null

    return import.meta.env.VITE_SHARE_URL+ '/share/'+code;
}

export async function loadShareUrl(code) {
    // console.log('loading share url', code)
    const data = await new Promise((resolve, reject) => {
        // Set a timeout (e.g., 8 seconds)
        const timeout = setTimeout(() => {
            reject(new Error('Timed out waiting for response from server'));
        }, 8000);

        socket.emit('shared', code, (response) => {
            clearTimeout(timeout);
            resolve(response);
        });
    }).catch(err => {
        // Optional: show error to user or log it
        console.error('Failed to load shared URL:', err.message);
        return null;
    });
    if (data===null) return false
    console.log('loaded shared orders data', data)
    const co = useChartOrderStore();
    const s = useStore()
    const ticker = `${data.chainId}|${data.symbol.route.exchange}|${data.symbol.base.a}|${data.symbol.quote.a}|${data.symbol.route.fee}`;
    const symbol = lookupSymbol(ticker)
    if (symbol===null) {
        console.error('could not find symbol for ticker', ticker)
        return false
    }
    s.chainId = data.chainId
    const prefs = usePrefStore()
    prefs.selectedSymbol = ticker
    for (const order of data.orders) {
        // force amount to be zero so that the user MUST enter a size before confirming the placement
        order.amount = 0
        order.amountIsTokenA = true
        order.valid = false
    }
    co.orders = data.orders
    changeIntervalSecs(data.period)
    onChartReady(()=>{
        setSymbol(symbol)
            .catch((e)=>console.error('could not set symbol', e))
    })
    track('shared')
    console.log('loaded orders', s.chainId, co.orders)
    return true;
}

export async function takeSnapshot() {
    const screenshotCanvas = await widget.takeClientScreenshot();
    return await new Promise((resolve) => screenshotCanvas.toBlob(resolve));
}
