<script setup lang="ts">
import {getMarketTypes, getPrices, MarketTypePrice} from "@/market";
import {ref, watch} from 'vue';
import {ArrowPathIcon} from '@heroicons/vue/24/outline';
import {useAutoRefresh} from '@/composables';
import {AcquiredType} from './AcquiredType';
import {RawAcquiredType} from './acquisition';
import AcquisitionResultTable from './AcquisitionResultTable.vue';
import BuyModal from './BuyModal.vue';
import SellModal from './SellModal.vue';

interface Props {
    items: RawAcquiredType[];
    ignoredColumns?: string[] | string;
    ledgerId?: string;
}

const props = defineProps<Props>();

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

const enriched = ref<AcquiredType[]>([]);

const refresh = async (itms: RawAcquiredType[] = props.items) => {
    if (itms.length === 0) {
        enriched.value = [];
        return;
    }

    const types = await getMarketTypes([...new Set(itms.map(i => i.type))]);
    const prices = await getPrices(types);

    enriched.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
        };
    });
};

watch(() => props.items, refresh, {immediate: true});

const {active: autoRefresh, toggle: toggleAutoRefresh} = useAutoRefresh(() => refresh(), 5 * 60 * 1000);
</script>

<template>
    <div class="flex">
        <div class="ms-auto flex">
            <button class="rounded-e-none" @click="refresh()">Refresh</button>
            <button class="rounded-s-none border-s-0 flex items-center" :class="{ 'bg-slate-700': autoRefresh }" title="Auto refresh" @click="toggleAutoRefresh">
                <ArrowPathIcon class="w-5 h-5" :class="{ 'animate-spin': autoRefresh }" />
            </button>
        </div>
    </div>
    <template v-if="enriched.length > 0">
        <AcquisitionResultTable :items="enriched" :ignoredColumns="ignoredColumns" @buy="(types, price, buy, sell) => buyModal?.open(types[0].type, { 'Price': price, 'Buy': buy, 'Sell': sell }, props.ledgerId)" @sell="types => sellModal?.open(types, props.ledgerId)" />
        <BuyModal ref="buyModal" />
        <SellModal ref="sellModal" />
    </template>
</template>