//#region src/components/pisellCountdown/utils.ts
const timeUnits = [
	["Y", 1e3 * 60 * 60 * 24 * 365],
	["M", 1e3 * 60 * 60 * 24 * 30],
	["D", 1e3 * 60 * 60 * 24],
	["H", 1e3 * 60 * 60],
	["m", 1e3 * 60],
	["s", 1e3],
	["S", 1]
];
/**
* 格式化时间字符串函数
* 该函数将给定的持续时间（以秒为单位）格式化为指定格式的时间字符串
* @param duration - 持续时间，单位为秒。
* @param format - 时间格式字符串，其中包含要显示的时间单位及其格式。例如："[HH] hours, [mm] minutes, [ss] seconds"。
*/
function formatTimeStr(duration, format) {
	let leftDuration = duration;
	const escapeRegex = /\[[^\]]*]/g;
	const keepList = (format.match(escapeRegex) || []).map((str) => str.slice(1, -1));
	const templateText = format.replace(escapeRegex, "[]");
	const replacedText = timeUnits.reduce((current, [name, unit]) => {
		if (current.includes(name)) {
			const value = Math.floor(leftDuration / unit);
			leftDuration -= value * unit;
			return current.replace(new RegExp(`${name}+`, "g"), (match) => {
				const len = match.length;
				return value.toString().padStart(len, "0");
			});
		}
		return current;
	}, templateText);
	let index = 0;
	return replacedText.replace(escapeRegex, () => {
		const match = keepList[index];
		index += 1;
		return match;
	});
}
//#endregion
export { formatTimeStr };
