<script>
import pluralize from "pluralize";

  import Link from "../Link.svelte";
  import Table from "../Table.svelte";
  
  import { createEventDispatcher } from 'svelte';
  import ActivityIcon from "../ActivityIcon.svelte";
  import ActivityDisplay from "../ActivityDisplay.svelte";
  import ActivityAmount from "../ActivityAmount.svelte";
  import ItemDisplay from "../ItemDisplay.svelte";
  import PointsBar from "../PointsBar.svelte";

  import dateStr from "../../utils/dateStr";
  
  export let period = {goals: []};
  export let activities = [];
  export let items = [];
  
  const dispatch = createEventDispatcher();

  let subActivityMap = {};

  function onOption(name, logId) {
    const log = period.logs.find(l => l.id === logId);
    const goal = period.goals.find(g => g.id === log.goalId)
    const activity = goal != null ? activities.find(a => a.id === goal.activityId) : null;
    const subActivity = activity != null ? activity.subActivities.find(s => s.id === log.subActivityId) : null;

    dispatch("option", {name, period, log, goal, activity, subActivity})
  }

  $: subActivityMap = activities.map(a => a.subActivities).flat().reduce((p, v) => ({...p, [v.id]: v}), {});
</script>

<Table 
  headers={["Date", "Goal", "Item", "Amount", "Points", "Options"]} 
  percentages={[25, 25, 15, 15, 5, 15]}
>
  {#each period.logs as log (log.id)}
    <tr>
      <td>{dateStr(log.date)}</td>
      <td class="ellipsis">
        <ActivityDisplay 
          activity={activities.find(a => a.id === (period.goals.find(g => g.id === log.goalId) || {}).activityId)}
          subActivity={subActivityMap[log.subActivityId]}
        />
      </td>
      <td>
        <ItemDisplay id={log.itemId} item={items.find(i => i.id === log.itemId)} />
      </td>
      <td>
        <ActivityAmount 
          amount={log.amount} 
          subActivity={subActivityMap[log.subActivityId]}
        />
      </td>
      <td>
        <Link on:click={() => onOption("periodlog.info", log.id)}>{log.score.total}</Link>
      </td>
      <td class="td-options">
        <Link on:click={() => onOption("periodlog.remove", log.id)}>Delete</Link>
      </td>
    </tr>
  {/each}
</Table>
