<script lang="ts" context="module">
  import mitt from "mitt";

  export type JobsEvents = {
    reload: undefined;
  };
  export const jobsEmitter = mitt<JobsEvents>();
</script>

<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[] = [];
  let timeout: number;
  async function updateJobs() {
    clearTimeout(timeout);
    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 };
      })
      .sort((j1, j2) => j1.id.localeCompare(j2.id));

    if (activeJobs.length) {
      timeout = setTimeout(updateJobs, 500);
    } else {
      timeout = setTimeout(updateJobs, 5000);
    }
  }
  updateJobs();

  jobsEmitter.on("reload", () => {
    updateJobs();
  });
</script>

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

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

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