import { DbSchema, LoopJob } from "../types"
import { QbitCapabilities, QbitTorrentInfo, QbitTransferInfo } from "../qbit/qbit.types"
import { readDb } from "../storage/jsondb"

export interface StatusSnapshot {
  qbit: {
    ok: boolean;
    version?: string;
    capabilities?: QbitCapabilities;
    lastError?: string;
  };
  torrents: QbitTorrentInfo[];
  transfer?: QbitTransferInfo;
  jobs: LoopJob[];
}

let snapshot: StatusSnapshot = {
  qbit: { ok: false },
  torrents: [],
  transfer: undefined,
  jobs: [],
};

export const setQbitStatus = (status: StatusSnapshot["qbit"]) => {
  snapshot.qbit = status;
};

export const setTorrentsStatus = (
  torrents: QbitTorrentInfo[],
  transfer?: QbitTransferInfo
) => {
  snapshot.torrents = torrents;
  snapshot.transfer = transfer;
};

export const refreshJobsStatus = async () => {
  const db: DbSchema = await readDb();
  snapshot.jobs = db.loopJobs;
  return snapshot.jobs;
};

export const getStatusSnapshot = async (): Promise<StatusSnapshot> => {
  await refreshJobsStatus();
  return snapshot;
};
