<script setup lang="ts">
import { MarketType, MarketTypePrice, getHistory, getMarketType, getMarketTypes, getPrice, getPrices, jitaId } from "@/market";
import { ScanResult, ScanResultTable, useMarkeyScanStore } from '@/market/scan';
import { BuyModal } from '@/market/track';
import { ref, watch } from 'vue';


const buyModal = ref<typeof BuyModal>();

const item = ref("");

const markeyScanStore = useMarkeyScanStore();
const items = ref<ScanResult[]>([]);
const addOrRelaod = async (type: MarketType) => {
    const typeID = type.id;
    const [history, price] = await Promise.all([
        getHistory(jitaId, typeID),
        getPrice(type)
    ]);
    const item = {
        type,
        history,
        buy: price.buy,
        sell: price.sell
    };

    if (items.value.some(i => i.type.id === typeID)) {
        items.value = items.value.map(i => i.type.id === typeID ? item : i);
    } else {
        items.value = [ ...items.value, item];
    }
}
const addItem = async () => {
    const type = await getMarketType(item.value.split('\t')[0]);
    
    item.value = "";
    addOrRelaod(type);
}


watch(items, async itms => markeyScanStore.setTypes(itms.map(i => i.type.id)));
watch(() => markeyScanStore.types, async t => {
    const typesToLoad = t.filter(t => !items.value.some(i => i.type.id === t));

    if (typesToLoad.length === 0) {
        return;
    }

    const prices = await getPrices(await getMarketTypes(typesToLoad));

    items.value = [...items.value, ...(await Promise.all(typesToLoad.map(async i => {
        const price = prices.find(p => p.type.id === i) as MarketTypePrice;
        const history = await getHistory(jitaId, i);
        
        return { id: i, history, ...price };
    })))];
}, { immediate: true });
</script>

<template>
    <div class="grid mb-2 mt-4">
        <div class="w-auto">
            <span>Item: </span>
            <input type="text" class="w-96" v-model="item" @keyup.enter="addItem" />
            <button class="justify-self-end ms-2" @click="addItem">Add</button>
        </div>
    </div>
    <template v-if="items.length > 0">
        <hr />
        <ScanResultTable :items="items" @buy="(type, buy, sell) => buyModal?.open(type, { 'Buy': buy, 'Sell': sell })" />
        <BuyModal ref="buyModal" />
    </template>
</template>