<script setup lang="ts">
import { MarketType, MarketTypeInput, MarketTypePrice, getHistory, getMarketTypes, jitaId, useApraisalStore } from "@/market";
import { BuyModal } from '@/market/acquisition';
import { ScanResult, ScanResultTable, createResult, useMarketScanStore } from '@/market/scan';
import { ref, watch } from 'vue';


const buyModal = ref<typeof BuyModal>();

const item = ref<MarketType>();

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

    if (items.value.some(i => i.type.id === typeID)) {
        items.value = items.value.map(i => i.type.id === typeID ? itm : i);
    } else {
        items.value = [ ...items.value, itm];
    }
}
const addItem = async () => {
    if (!item.value) {
        // TODO error
        return;
    }

    addOrRelaod(item.value);
    item.value = undefined;
}
const removeItem = (type: MarketType) => {
    items.value = items.value.filter(i => i.type.id !== type.id);
}


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 apraisalStore.getPrices(await getMarketTypes(typesToLoad));

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

<template>
    <div class="grid mb-2 mt-4">
        <div class="w-auto flex">
            <span>Item: </span>
            <MarketTypeInput class="ms-2" v-model="item" @submit="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 })" @remove="removeItem" />
        <BuyModal ref="buyModal" />
    </template>
</template>@/market/acquisition