<script lang="ts">
  import type { IJob } from "upend/types";
  import { fade } from "svelte/transition";
import ProgessBar from "../utils/ProgessBar.svelte";

  interface JobWithId extends IJob {
    id: string;
  }

  let jobs: JobWithId[] = [];
  let activeJobs: JobWithId[] = [];
  async function updateJobs() {
    let request = await fetch("/api/jobs");
    jobs = await request.json();

    activeJobs = Object.entries(jobs)
      .filter(([_, job]) => job.state == "InProgress")
      .map(([id, job]) => {
        return { id, ...job };
      });

    if (activeJobs.length) {
      setTimeout(updateJobs, 500);
    } else {
      setTimeout(updateJobs, 5000);
    }
  }
  updateJobs();
</script>

{#each activeJobs as job (job.id)}
  <div class="job" transition:fade>
    <div class="job-label">{job.title}</div>
    <ProgessBar value={job.progress}>
      {Math.round(job.progress)}%
    </ProgessBar>
  </div>
{/each}

<style scoped lang="scss">
  .job {
    display: flex;

    .job-label {
      white-space: nowrap;
      margin-right: 2em;
    }
  }
</style>
