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

jingrow.ui.form.on("User Permission", {
	setup: (frm) => {
		frm.set_query("allow", () => {
			return {
				filters: {
					issingle: 0,
					istable: 0,
				},
			};
		});

		frm.set_query("applicable_for", () => {
			return {
				query: "jingrow.core.pagetype.user_permission.user_permission.get_applicable_for_pagetype_list",
				pagetype: frm.pg.allow,
			};
		});
	},

	refresh: (frm) => {
		frm.add_custom_button(__("View Permitted Documents"), () =>
			jingrow.set_route("query-report", "Permitted Documents For User", {
				user: frm.pg.user,
			})
		);
		frm.trigger("set_applicable_for_constraint");
		frm.trigger("toggle_hide_descendants");
	},

	allow: (frm) => {
		if (frm.pg.allow) {
			if (frm.pg.for_value) {
				frm.set_value("for_value", null);
			}
			frm.trigger("toggle_hide_descendants");
		}
	},

	apply_to_all_pagetypes: (frm) => {
		frm.trigger("set_applicable_for_constraint");
	},

	set_applicable_for_constraint: (frm) => {
		frm.toggle_reqd("applicable_for", !frm.pg.apply_to_all_pagetypes);

		if (frm.pg.apply_to_all_pagetypes && frm.pg.applicable_for) {
			frm.set_value("applicable_for", null, null, true);
		}
	},

	toggle_hide_descendants: (frm) => {
		let show = jingrow.boot.nested_set_pagetypes.includes(frm.pg.allow);
		frm.toggle_display("hide_descendants", show);
	},
});
