<script setup lang="ts">

import {TransferTypes} from "@/transaction/transaction.ts";
import {LedgerLabel, systemLedger, useLedgersStore} from "@/ledger";
import {getMarketType, IskLabel, MarketTypeLabel} from "@/market";
import {computedAsync} from "@vueuse/core";
import {TransferResponse} from "@/generated/mammon";

type TransferWithValue = TransferResponse & { marketTypeId: number; };

interface Props {
  transfers?: TransferResponse[]
}

const props = defineProps<Props>();

const ledgersStore = useLedgersStore();

const sortedArray = computedAsync(async () => {
  if (!props.transfers) {
    return [];
  }

  return (await Promise.all(props.transfers.map(async (transfer: TransferWithValue, index) => {
    const fromLedger = ledgersStore.findById(transfer.fromLedgerId) ?? systemLedger
    const toLedger = ledgersStore.findById(transfer.toLedgerId) ?? systemLedger

    const item = transfer.marketTypeId ? await getMarketType(transfer.marketTypeId) : undefined;

    return {
      ...transfer,
      order: index,
      fromLedger,
      toLedger,
      itemName: item ? item.name : '',
      fromLedgerName: fromLedger.name,
      toLedgerName: toLedger.name
    }
  }))).sort((a, b) => a.order - b.order)
}, []);

</script>

<template>
  <div>
    <table>
      <thead>
      <tr>
        <th>From</th>
        <th>To</th>
        <th>Item</th>
        <th>Quantity/Amount</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="t in sortedArray">
        <td>
          <LedgerLabel :ledger="t.fromLedger" />
        </td>
        <td>
          <LedgerLabel :ledger="t.toLedger" />
        </td>
        <template v-if="t.type === TransferTypes.Item">
          <td>
            <MarketTypeLabel :id="t.marketTypeId" :name="t.itemName" />
          </td>
          <td class="text-right">{{ t.quantity }}</td>
        </template>
        <template v-else-if="t.type === TransferTypes.Isk">
          <td colspan="2" class="text-right">
            <IskLabel :amount="t.amount" :colored="false" />
          </td>
        </template>
      </tr>
      </tbody>
    </table>
  </div>
</template>