// Copyright (c) 2018, JINGROW
// For license information, please see license.txt

jingrow.ui.form.on("Prepared Report", {
	render_filter_values: function (frm, filters) {
		var wrapper = $(frm.fields_dict["filter_values"].wrapper).empty();

		let filter_table = $(`<table class="table table-bordered">
			<thead>
				<tr>
					<td>${__("Filter")}</td>
					<td>${__("Value")}</td>
				</tr>
			</thead>
			<tbody></tbody>
		</table>`);

		Object.keys(filters).forEach((key) => {
			const filter_row = $(`<tr>
				<td>${jingrow.model.unscrub(key)}</td>
				<td>${filters[key]}</td>
			</tr>`);
			filter_table.find("tbody").append(filter_row);
		});

		wrapper.append(filter_table);
	},

	refresh: function (frm) {
		frm.disable_save();

		const filters = JSON.parse(frm.pg.filters);
		if (!$.isEmptyObject(filters)) {
			frm.toggle_display(["filter_values"], 1);
			frm.events.render_filter_values(frm, filters);
		}

		// always keep report_name hidden - we do this as we can't set mandatory and hidden
		// property on a pagefield at the same time
		frm.toggle_display(["report_name"], 0);

		if (frm.pg.status == "Completed") {
			frm.page.set_primary_action(__("Show Report"), () => {
				jingrow.route_options = { prepared_report_name: frm.pg.name };
				jingrow.set_route("query-report", frm.pg.report_name);
			});
		}
	},
});
