<script lang="ts">
  import type { GoalCompositionMode } from "../models/goal";
  import type { LogResult } from "../models/log";

  interface CompositionItem {
    link: string
    amount: number
    name: string
  }

  export let logs: LogResult[] = [];
  export let mode: GoalCompositionMode = "item";
  export let ignoreZeroWeight: boolean = false;

  let list: CompositionItem[] = [];

  $: {
    const map: {[k: string]: CompositionItem} = {}
  
    if (mode === "item") {
      for (const log of logs) {
        if (log.itemCounted !== false) {
          const item = log.item;
          if (!ignoreZeroWeight || item.groupWeight > 0) {
            if (!map[item.id]) {
              map[item.id] = {name: item.name, amount: log.itemAmount, link: `/items#${item.id}`};
            } else {
              map[item.id].amount += log.itemAmount;
            }
          }
        }

        if (log.secondaryItem && log.secondaryItemCounted !== false) {
          const item = log.secondaryItem;
          if (!ignoreZeroWeight || item.groupWeight > 0) {
            if (!map[item.id]) {
              map[item.id] = {name: item.name, amount: log.secondaryItemAmount, link: `/items#${item.id}`};
            } else {
              map[item.id].amount += log.secondaryItemAmount;
            }
          }
        }
      }
    } else {
      for (const log of logs) {
        const task = log.task;

        const amount = log.secondaryItem ? log.secondaryItemAmount + log.itemAmount : log.itemAmount;

        if (!map[task.id]) {
          map[task.id] = {name: task.name, amount, link: `/questlog#${task.projectId}`};
        } else {
          map[task.id].amount += amount;
        }
      }
    }
  
    list = Object.keys(map).sort((a, b) => map[b].amount - map[a].amount).map(k => map[k]).filter(e => e.amount > 0);
  }
</script>

<div class="composition">
  {#each list as item (item.name)}
    <div class="item">
      <span class="amount">{item.amount}x&nbsp;</span>
      <a href={item.link}>{item.name}</a>
    </div>
  {/each}
</div>

<style>
  div.composition {
    padding: 0.25em 0ch;
    color: #555;
    font-size: 0.75em;
  }

  div.item {
    padding: 0.125em 0.5ch;
    display: inline-block;
  }

  span.amount {
    color: #777;
  }

  a {
    color: inherit;
  }
</style>