<script lang="ts">
  import type { ProjectResult } from "../models/project";
  import type { GoalResult } from "../models/goal";

  export let project: ProjectResult | undefined | null = void(0);
  export let goal: GoalResult | undefined | null = void(0);

  let progressAmount: number = 0;
  let progressTarget: number = 0;
  let timeProgress: number | null = null;

  let boat: number | null = null;
  let boatNegative = false;
  let boatPositive = false;
  let boatString: string | null = null;

  $: {
    if (project != null) {
      progressAmount = (project.tasks||[]).map(t => (t.active || t.statusTag === "to do" || t.statusTag === "on hold") 
        ? Math.min(t.completedAmount, t.itemAmount) * (t.item.groupWeight || 1) 
        : t.itemAmount * (t.item.groupWeight || 1)
      ).reduce((n,m) => n+m, 0);

      progressTarget = Math.max((project.tasks||[]).map(t => t.itemAmount * (t.item.groupWeight || 1)).reduce((n,m) => n+m, 0), 1);
    
      progressAmount = Math.max(progressAmount - project.subtractAmount, 0);
      progressTarget = Math.max(progressTarget - project.subtractAmount, 0);

      if (project.endTime) {
        const start = Date.parse(project.startTime || project.createdTime);
        const end = Date.parse(project.endTime);
        const now = Math.max(Math.min(Date.now(), end), start);

        timeProgress = (now - start) / (end - start);
      } else {
        timeProgress = null;
      }
    }

    if (goal != null) {
      const start = Date.parse(goal.startTime);
      const end = Date.parse(goal.endTime);
      const now = Math.max(Math.min(Date.now(), end), start);

      progressAmount = goal.completedAmount;
      progressTarget = goal.amount;
      timeProgress = (now - start) / (end - start);
    }
  }

  $: {
    if (timeProgress != null) {
      const boatTarget = Math.ceil(timeProgress * progressTarget);
      
      boat = progressAmount - boatTarget;
    } else {
      boat = null;
    }
  }

  $: {
    if (boat != null) {
      boatNegative = boat < 0;
      boatPositive = boat > 0;

      boatString = Math.round(boat).toString(10);
      if (boatPositive) {
        boatString = '+' + boatString;
      }
    }
  }
</script>

<div class="progress">
  <div class="amount">{progressAmount}</div>
  <div class="slash">/</div>
  <div class="target">{progressTarget}</div>
  {#if boat}
    <div class="boat" class:positive={boatPositive} class:negative={boatNegative}>
      ({boatString})
    </div>
  {/if}
</div>

<style>
  div.progress {
    padding: 0 0.25ch;
    color: #555;
  }
  
  div.progress > div {
    display: inline-block;
  }

  div.slash {
    padding: 0 0.125ch;
    color: #333;
  }

  div.boat {
    padding-left: 0.25ch;
  }

  div.boat.negative {
    color: #852a24;
  }
  div.boat.positive {
    color: #484;
  }
</style>