<script setup lang="ts">
import { useStorage } from '@vueuse/core';
import { onMounted, ref, watch } from 'vue';
import { MarketOrderHistory, MarketResult, getHistory, jitaId } from ".";
import MarketReultTable from "./MarketResultTable.vue";
import { MarketType, getMarketType, getMarketTypes } from "./type";

type MarketItemStorage = {
    typeID: number;
    history: MarketOrderHistory[];
}

const item = ref("");
const itemsStorage = useStorage<MarketItemStorage[]>('market-items', []);
const items = ref<MarketResult[]>([]);
const addOrRelaod = async (type: MarketType) => {
    const typeID = type.id;
    const history = await getHistory(jitaId, typeID);
    const item = { type, history };

    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 reloadAll = async () => {
    items.value = await Promise.all(items.value.map( async i => ({ ...i, history: await getHistory(jitaId, i.type.id) })));
}
const addItem = async () => {
    const type = await getMarketType(item.value.split('\t')[0]);
    
    item.value = "";
    addOrRelaod(type);
}

watch(items, itms => itemsStorage.value = itms.map(i => ({ typeID: i.type.id, history: i.history })));
onMounted(async () => {
    const types = await getMarketTypes(itemsStorage.value.map(i => i.typeID));

    items.value = itemsStorage.value.map(i => ({ ...i, type: types.find(t => t.id === i.typeID) as MarketType }));
})
</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 />
        <MarketReultTable :items="items" @relaod="type => addOrRelaod(type)" @relaodAll="reloadAll" />
    </template>
</template>