import type { CronJob, InvalidJob } from './schedules'

const jobs = new Map<string, CronJob>()
const listeners = new Set<() => void>()

let invalidJobs: InvalidJob[] = []

export function setJobs(newJobs: CronJob[]) {
  jobs.clear()
  for (const job of newJobs) {
    jobs.set(job.id, job)
  }
  broadcast()
}

export function setInvalidJobs(newInvalid: InvalidJob[]) {
  invalidJobs = newInvalid
}

export function getJob(id: string): CronJob | undefined {
  return jobs.get(id)
}

export function getAllJobs(): CronJob[] {
  return Array.from(jobs.values())
}

export function getInvalidJobs(): InvalidJob[] {
  return invalidJobs
}

export function broadcast() {
  listeners.forEach(cb => cb())
}

export function onChange(cb: () => void): () => void {
  listeners.add(cb)
  return () => listeners.delete(cb)
}
