<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";
  import api from "../../lib/api";

  interface JobWithId extends IJob {
    id: string;
  }

  let jobs: IJob[] = [];
  let activeJobs: JobWithId[] = [];

  export let active = 0;
  $: active = activeJobs.length;

  let timeout: NodeJS.Timeout;
  async function updateJobs() {
    clearTimeout(timeout);
    jobs = await api.fetchJobs();

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

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

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

{#each activeJobs.slice(0, 3) as job (job.id)}
  <div class="job" transition:fade>
    <div class="job-label">{job.title}</div>
    <ProgessBar value={job.progress} />
  </div>
{/each}
{#if activeJobs.length > 3}
  <div class="job-annotation">
    + {activeJobs.length - 3} more jobs...
  </div>
{/if}

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

    .job-label {
      white-space: nowrap;
      margin-right: 2em;
    }
  }

  .job-annotation {
    opacity: 0.75;
  }
</style>
