
function parseRange (str) {
	const rx = /^[\[(].*,.*[)\]]$/

	if (rx.test(str)) {
		const lower_inclusive = str[0] == '[';
		const upper_inclusive = str[str.length-1] == ']';
		const [ lower, upper ] = str.slice(1,-1).split(",");
		return {
			upper,
			lower,
			upper_inclusive,
			lower_inclusive
		};
	}
}

function parseValidity (str) {
	const range = parseRange(str);

	if (range) {
		ts0 = range.lower ? new Date(range.lower) : null;
		ts1 = range.upper ? new Date(range.upper) : null;

		return {
			...range,
			lower: ts0,
			upper: ts1
		};
	}
}

function withinValidity (range, ts) {
	if (!ts) {
		ts = new Date();
	}

	if (typeof range === "string") {
		range = parseValidity(range);
	}

	if (range.lower) {
		if (range.lower_inclusive) {
			if (!(range.lower <= ts)) {
				return false;
			}
		} else {
			if (!(range.lower < ts)) {
				return false;
			}
		}
	}

	if (range.upper) {
		if (range.upper_inclusive) {
			if (!(range.upper >= ts)) {
				return false;
			}
		} else {
			if (!(range.upper > ts)) {
				return false;
			}
		}
	}

	return true;
}

module.exports = {
	parseRange,
	parseValidity,
	withinValidity
}

