import { getJsDateFromExcel } from "excel-date-to-js";

export const excelDateStuff = (
	serial: number,
	defaultTime = 800,
	time?: number,
) => {
	if (typeof serial !== "number" || serial <= 0) {
		return "invalid Date";
	}

	// Get base date from Excel serial (this gives you UTC midnight)
	const excelTime = excelSerialToTime(serial);
	const finalTime = time ?? excelTime ?? defaultTime;

	const date = getJsDateFromExcel(Math.floor(serial));

	const localOffset = new Date().getTimezoneOffset() / 60;
	const hours = Math.floor(finalTime / 100);
	const minutes = finalTime % 100;

	// Set the time in UTC
	date.setUTCHours(hours + localOffset);
	date.setUTCMinutes(minutes);
	date.setUTCSeconds(0);
	date.setUTCMilliseconds(0);

	//console.log(date.toISOString(), serial, time);
	return date.toISOString();
};

const excelSerialToTime = (serial: number): number | null => {
	const fraction = serial % 1;

	if (fraction <= 0) {
		return null;
	}

	const totalMinutes = Math.round(fraction * 24 * 60);
	const hours = Math.floor(totalMinutes / 60);
	const minutes = totalMinutes % 60;

	return hours * 100 + minutes;
};
