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

jingrow.ui.form.on("Page Naming Rule", {
	refresh: function (frm) {
		frm.trigger("document_type");
		frm.last_counter_value = frm.pg.counter;
		frm.skip_before_save = false;
	},
	before_save: function (frm) {
		if (frm.is_new() || frm.skip_before_save || frm.last_counter_value === frm.pg.counter)
			return;

		jingrow.validated = false;
		jingrow.warn(
			__("Are you sure?"),
			__("Updating counter may lead to document name conflicts if not done properly"),
			() => {
				frm.skip_before_save = true;
				frm.save();
			},
			__("Proceed"),
			false
		);
	},
	document_type: (frm) => {
		// update the select field options with fieldnames
		if (frm.pg.document_type) {
			jingrow.model.with_pagetype(frm.pg.document_type, () => {
				let fieldnames = jingrow
					.get_meta(frm.pg.document_type)
					.fields.filter((d) => {
						return jingrow.model.no_value_type.indexOf(d.fieldtype) === -1;
					})
					.map((d) => {
						return { label: `${d.label} (${d.fieldname})`, value: d.fieldname };
					});
				frm.fields_dict.conditions.grid.update_pagefield_property(
					"field",
					"options",
					fieldnames
				);
			});
		}
	},
});
