<script setup lang="ts">
import { MarketTypePrice, getMarketTypes, useApraisalStore } from "@/market";
import { BuyModal, SellModal, TrackResultTable, TrackedItem, useTrackedItemStore } from '@/market/track';
import { ref, watch } from 'vue';

const buyModal = ref<typeof BuyModal>();
const sellModal = ref<typeof SellModal>();


const apraisalStore = useApraisalStore();
const trackedItemStore = useTrackedItemStore();
const items = ref<TrackedItem[]>([]);

watch(() => trackedItemStore.items.value, async itms => {
    if (itms.length === 0) {
        return;
    }

    const prices = await apraisalStore.getPrices(await getMarketTypes(itms.map(i => i.typeID)));

    items.value = itms.map(i => {
        const price = prices.find(p => p.type.id === i.typeID) as MarketTypePrice;
        
        return { ...i, ...price };
    });
}, { immediate: true })

</script>

<template>
    <div class="mt-4">
        <template v-if="items.length > 0">
            <TrackResultTable :items="items" @buy="(type, price, buy, sell) => buyModal?.open(type, {  'Price': price, 'Buy': buy, 'Sell': sell })" @sell="type => sellModal?.open(type)" />
            <BuyModal ref="buyModal" />
            <SellModal ref="sellModal" />
        </template>
    </div>
</template>