import events from './events.js';

export default function navigate(path, query, options = {}) {
	const curatedQuery = Object.fromEntries(Object.entries(query || {}).map(([key, value]) => (value === undefined ? null : [key, value])).filter(Boolean));

	const queryString = new URLSearchParams({
		...(options.preserveQuery ? Object.fromEntries(new URL(window.location).searchParams.entries()) : {}),
		...curatedQuery,
	}).toString();

	const url = queryString
		? `${path}?${queryString
			.replace(/%2C/g, ',') // URLSearchParams encodes commas and colons, we don't want that
			.replace(/%3A/g, ':')}`
		: path;

	if (options.redirect) {
		window.location.href = url;
	}
	else if (options.replace) {
		history.replaceState({}, '', url);
	}
	else {
		history.pushState({}, '', url);
	}

	events.emit('route', url);
}
