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

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

const item = ref("");
const items = useStorage<MarketItem[]>('market-items', []);
const result = computedAsync<MarketResult[]>(() => Promise.all(items.value.map(async (i) => {
    const [type, quartils] = await Promise.all([
        getMarketType(i.typeID), 
        getHistoryQuartils(i.history)
    ]);

    return {
        type,
        q1: quartils.q1,
        median: quartils.median,
        q3: quartils.q3
    };
})), []);
const addOrRelaod = async (typeID: number) => {
    const history = await getHistory(jitaId, typeID);
    const item = { typeID, history };

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

<template>
    <div class="grid mb-2 mt-4">
        <div>
            <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="result.length > 0">
        <hr />
        <MarketReultTable :result="result" @relaod="id => addOrRelaod(id)" />
    </template>
</template>