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

jingrow.ui.form.on("Client Script", {
	setup(frm) {
		frm.get_field("sample").html(SAMPLE_HTML);
	},
	refresh(frm) {
		if (frm.pg.dt && frm.pg.script) {
			frm.add_custom_button(__("Go to {0}", [frm.pg.dt]), () =>
				jingrow.set_route("List", frm.pg.dt, "List")
			);
		}

		if (frm.pg.view == "Form") {
			frm.add_custom_button(__("Add script for Child Table"), () => {
				jingrow.model.with_pagetype(frm.pg.dt, () => {
					const child_tables = jingrow.meta
						.get_pagefields(frm.pg.dt, null, {
							fieldtype: "Table",
						})
						.map((df) => df.options);

					const d = new jingrow.ui.Dialog({
						title: __("Select Child Table"),
						fields: [
							{
								label: __("Select Child Table"),
								fieldtype: "Link",
								fieldname: "cdt",
								options: "PageType",
								get_query: () => {
									return {
										filters: {
											istable: 1,
											name: ["in", child_tables],
										},
									};
								},
							},
						],
						primary_action: ({ cdt }) => {
							cdt = d.get_field("cdt").value;
							frm.events.add_script_for_pagetype(frm, cdt);
							d.hide();
						},
					});

					d.show();
				});
			});

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

		frm.set_query("dt", {
			filters: {
				istable: 0,
			},
		});
	},

	dt(frm) {
		frm.toggle_display("view", !jingrow.boot.single_types.includes(frm.pg.dt));

		if (!frm.pg.script) {
			frm.events.add_script_for_pagetype(frm, frm.pg.dt);
		}

		if (frm.pg.script && !frm.pg.script.includes(frm.pg.dt)) {
			frm.pg.script = "";
			frm.events.add_script_for_pagetype(frm, frm.pg.dt);
		}
	},

	view(frm) {
		let has_form_boilerplate = frm.pg.script.includes("jingrow.ui.form.on");
		if (frm.pg.view === "List" && has_form_boilerplate) {
			frm.set_value("script", "");
		}
		if (frm.pg.view === "Form" && !has_form_boilerplate) {
			frm.trigger("dt");
		}
	},

	add_script_for_pagetype(frm, pagetype) {
		if (!pagetype) return;
		let boilerplate = `
jingrow.ui.form.on('${pagetype}', {
	refresh(frm) {
		// your code here
	}
})
		`.trim();
		let script = frm.pg.script || "";
		if (script) {
			script += "\n\n";
		}
		frm.set_value("script", script + boilerplate);
	},
});

const SAMPLE_HTML = `<h3>Client Script Help</h3>
<p>Client Scripts are executed only on the client-side (i.e. in Forms). Here are some examples to get you started</p>
<pre><code>

// fetch local_tax_no on selection of customer
// cur_frm.add_fetch(link_field,  source_fieldname,  target_fieldname);
cur_frm.add_fetch("customer",  "local_tax_no',  'local_tax_no');

// additional validation on dates
jingrow.ui.form.on('Task',  'validate',  function(frm) {
    if (frm.pg.from_date &lt; get_today()) {
        msgprint('You can not select past date in From Date');
        validated = false;
    }
});

// make a field read-only after saving
jingrow.ui.form.on('Task',  {
    refresh: function(frm) {
        // use the __islocal value of pg,  to check if the pg is saved or not
        frm.set_df_property('myfield',  'read_only',  frm.pg.__islocal ? 0 : 1);
    }
});

// additional permission check
jingrow.ui.form.on('Task',  {
    validate: function(frm) {
        if(user=='user1@example.com' &amp;&amp; frm.pg.purpose!='Material Receipt') {
            msgprint('You are only allowed Material Receipt');
            validated = false;
        }
    }
});

// calculate sales incentive
jingrow.ui.form.on('Sales Invoice',  {
    validate: function(frm) {
        // calculate incentives for each person on the deal
        total_incentive = 0
        $.each(frm.pg.sales_team,  function(i,  d) {
            // calculate incentive
            var incentive_percent = 2;
            if(frm.pg.base_grand_total &gt; 400) incentive_percent = 4;
            // actual incentive
            d.incentives = flt(frm.pg.base_grand_total) * incentive_percent / 100;
            total_incentive += flt(d.incentives)
        });
        frm.pg.total_incentive = total_incentive;
    }
})

</code></pre>`;
