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

jingrow.ui.form.on("Server Script", {
	setup: function (frm) {
		frm.trigger("setup_help");
	},
	refresh: function (frm) {
		if (frm.pg.script_type != "Scheduler Event") {
			frm.dashboard.hide();
		}

		if (!frm.is_new()) {
			frm.add_custom_button(__("Compare Versions"), () => {
				new jingrow.ui.DiffView("Server Script", "script", frm.pg.name);
			});
		}

		frm.call("get_autocompletion_items")
			.then((r) => r.message)
			.then((items) => {
				frm.set_df_property("script", "autocompletions", items);
			});

		frm.trigger("check_safe_exec");
	},

	check_safe_exec(frm) {
		jingrow.xcall("jingrow.core.pagetype.server_script.server_script.enabled").then((enabled) => {
			if (enabled === false) {
				let pgs_link =
					"https://framework.jingrow.com/pages/user/en/desk/scripting/server-script";
				let pgs = `<a href=${pgs_link}>${__("Official Documentation")}</a>`;

				frm.dashboard.clear_comment();
				let msg = __("Server Scripts feature is not available on this site.") + " ";
				msg += __("To enable server scripts, read the {0}.", [pgs]);
				frm.dashboard.add_comment(msg, "yellow", true);
			}
		});
	},

	setup_help(frm) {
		frm.get_field("help_html").html(`
<h4>PageType Event</h4>
<p>Add logic for standard pagetype events like Before Insert, After Submit, etc.</p>
<pre>
	<code>
# set property
if "test" in pg.description:
	pg.status = 'Closed'


# validate
if "validate" in pg.description:
	raise jingrow.ValidationError

# auto create another document
if pg.allocated_to:
	jingrow.get_pg(dict(
		pagetype = 'ToDo'
		owner = pg.allocated_to,
		description = pg.subject
	)).insert()
</code>
</pre>

<hr>

<h4>API Call</h4>
<p>Respond to <code>/api/action/&lt;method-name&gt;</code> calls, just like whitelisted methods</p>
<pre><code>
# respond to API

if jingrow.form_dict.message == "ping":
	jingrow.response['message'] = "pong"
else:
	jingrow.response['message'] = "ok"
</code></pre>

<hr>

<h4>Permission Query</h4>
<p>Add conditions to the where clause of list queries.</p>
<pre><code>
# generate dynamic conditions and set it in the conditions variable
tenant_id = jingrow.db.get_value(...)
conditions = f'tenant_id = {tenant_id}'

# resulting select query
select name from \`tabPerson\`
where tenant_id = 2
order by creation desc
</code></pre>
`);
	},
});
