import type { InferResultType } from "@/utils/drizzle";

export enum PrinterStatus {
	IDLE = 0,
	OUT_OF_ORDER = 1,
	RESERVED = 2,
}

export function derivePrinterStatus(
	printer: InferResultType<"printers", { printJobs: true }>,
) {
	if (printer.status === PrinterStatus.OUT_OF_ORDER) {
		return PrinterStatus.OUT_OF_ORDER;
	}

	const activePrintJob = printer.printJobs[0];

	if (!activePrintJob || activePrintJob.aborted) {
		return PrinterStatus.IDLE;
	}

	const now = Date.now();
	const startAt = new Date(activePrintJob.startAt).getTime();
	const endAt = startAt + activePrintJob.durationInMinutes * 60 * 1000;
	if (now < endAt) {
		return PrinterStatus.RESERVED;
	}

	return PrinterStatus.IDLE;
}

export function translatePrinterStatus(status: PrinterStatus) {
	switch (status) {
		case PrinterStatus.IDLE:
			return "Verfügbar";
		case PrinterStatus.OUT_OF_ORDER:
			return "Außer Betrieb";
		case PrinterStatus.RESERVED:
			return "Reserviert";
	}
}
