<script setup lang="ts">
import { MarketTypePrice, getMarketTypes, useApraisalStore } from "@/market";
import { AcquiredType, AcquisitionResultTable, BuyModal, SellModal, useAcquiredTypesStore } from '@/market/acquisition';
import { ref, watch } from 'vue';

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


const apraisalStore = useApraisalStore();
const acquiredTypesStore = useAcquiredTypesStore();
const items = ref<AcquiredType[]>([]);

watch(() => acquiredTypesStore.acquiredTypes, async itms => {
    if (itms.length === 0) {
        return;
    }

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

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

</script>

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