const optionsAdvancedSearch = {
	blogCategories: {
		destination: [
			{
				field: "destination",
				condition_type: "eq",
				condition: "where",
			},
		],
		id: [
			{
				field: "id",
				condition_type: "eq",
				condition: "where",
			},
		],
	},
};

const getFilters = (model, fieldOption) => {
	const filters = [];
	const selectedOption = optionsAdvancedSearch[fieldOption];

	const _PushFilters = (filter, key) => {
		if (Array.isArray(model[key])) {
			filter.value = model[key].map((el) => el.id).join(" ");
			if (!filter.value.trim()) return;
		} else if (typeof model[key] === "boolean") {
			filter.value = Number(model[key]);
		} else {
			filter.value = (model[key] && model[key].value) || model[key];
		}

		filters.push(filter);
	};

	Object.keys(model).forEach((key) => {
		if (model[key] === null) return;

		const selectedField = selectedOption && selectedOption[key];
		const filter = {
			field: key,
		};

		if (selectedField) {
			selectedField.forEach((fieldOption) => {
				_PushFilters({ ...filter, ...fieldOption }, key);
			});
		} else _PushFilters(filter, key);
	});

	return filters;
};
const serialize = (filter_group) => {
	const criteria = {};
	const group = "[filter_group][0]";

	Object.keys(filter_group).forEach((group_key) => {
		filter_group[group_key].forEach((el, index) => {
			Object.keys(el).forEach((key) => {
				criteria[`${group}[${group_key}][${index}][${key}]`] = el[key];
			});
		});
	});

	return Object.keys(criteria)
		.map((key) => `criteria${key}=${criteria[key]}`)
		.join("&");
};

window.getFilters = getFilters;
window.serialize = serialize;
