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

const DATE_BASED_EVENTS = ["Days Before", "Days After"];

jingrow.notification = {
	setup_fieldname_select: function (frm) {
		// get the pagetype to update fields
		if (!frm.pg.document_type) {
			return;
		}

		jingrow.model.with_pagetype(frm.pg.document_type, function () {
			let get_select_options = function (df, parent_field) {
				// Append parent_field name along with fieldname for child table fields
				let select_value = parent_field ? df.fieldname + "," + parent_field : df.fieldname;

				return {
					value: select_value,
					label: df.fieldname + " (" + __(df.label, null, df.parent) + ")",
				};
			};

			let get_date_change_options = function () {
				let date_options = $.map(fields, function (d) {
					return d.fieldtype == "Date" || d.fieldtype == "Datetime"
						? get_select_options(d)
						: null;
				});
				// append creation and modified date to Date Change field
				return date_options.concat([
					{ value: "creation", label: `creation (${__("Created On")})` },
					{ value: "modified", label: `modified (${__("Last Modified Date")})` },
				]);
			};

			let fields = jingrow.get_pg("PageType", frm.pg.document_type).fields;
			let options = $.map(fields, function (d) {
				return jingrow.model.no_value_type.includes(d.fieldtype)
					? null
					: get_select_options(d);
			});

			// set value changed options
			frm.set_df_property("value_changed", "options", [""].concat(options));
			frm.set_df_property("set_property_after_alert", "options", [""].concat(options));

			// set date changed options
			frm.set_df_property("date_changed", "options", get_date_change_options());

			let receiver_fields = [];
			if (frm.pg.channel === "Email") {
				receiver_fields = $.map(fields, function (d) {
					// Add User and Email fields from child into select dropdown
					if (jingrow.model.table_fields.includes(d.fieldtype)) {
						let child_fields = jingrow.get_pg("PageType", d.options).fields;
						return $.map(child_fields, function (df) {
							return df.options == "Email" ||
								(df.options == "User" && df.fieldtype == "Link")
								? get_select_options(df, d.fieldname)
								: null;
						});
						// Add User and Email fields from parent into select dropdown
					} else {
						return d.options == "Email" ||
							(d.options == "User" && d.fieldtype == "Link")
							? get_select_options(d)
							: null;
					}
				});
			} else if (["WhatsApp", "SMS"].includes(frm.pg.channel)) {
				receiver_fields = $.map(fields, function (d) {
					return d.options == "Phone" ? get_select_options(d) : null;
				});
			}

			// set email recipient options
			frm.fields_dict.recipients.grid.update_pagefield_property(
				"receiver_by_document_field",
				"options",
				[""].concat(["owner"]).concat(receiver_fields)
			);
		});
	},
	setup_example_message: function (frm) {
		let template = "";
		if (frm.pg.channel === "Email") {
			template = `<h5>Message Example</h5>

<pre>&lt;h3&gt;Order Overdue&lt;/h3&gt;

&lt;p&gt;Transaction {{ pg.name }} has exceeded Due Date. Please take necessary action.&lt;/p&gt;

&lt;!-- show last comment --&gt;
{% if comments %}
Last comment: {{ comments[-1].comment }} by {{ comments[-1].by }}
{% endif %}

&lt;h4&gt;Details&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Customer: {{ pg.customer }}
&lt;li&gt;Amount: {{ pg.grand_total }}
&lt;/ul&gt;
</pre>
			`;
		} else if (["Slack", "System Notification", "SMS"].includes(frm.pg.channel)) {
			template = `<h5>Message Example</h5>

<pre>*Order Overdue*

Transaction {{ pg.name }} has exceeded Due Date. Please take necessary action.

<!-- show last comment -->
{% if comments %}
Last comment: {{ comments[-1].comment }} by {{ comments[-1].by }}
{% endif %}

*Details*

• Customer: {{ pg.customer }}
• Amount: {{ pg.grand_total }}
</pre>`;
		}
		if (template) {
			frm.set_df_property("message_examples", "options", template);
		}
	},
};

jingrow.ui.form.on("Notification", {
	onload: function (frm) {
		frm.set_query("document_type", function () {
			if (DATE_BASED_EVENTS.includes(frm.pg.event)) return;

			return {
				filters: {
					istable: 0,
				},
			};
		});
		frm.set_query("print_format", function () {
			return {
				filters: {
					pg_type: frm.pg.document_type,
				},
			};
		});
	},
	refresh: function (frm) {
		jingrow.notification.setup_fieldname_select(frm);
		jingrow.notification.setup_example_message(frm);

		frm.add_fetch("sender", "email_id", "sender_email");
		frm.set_query("sender", () => {
			return {
				filters: {
					enable_outgoing: 1,
				},
			};
		});
		frm.get_field("is_standard").toggle(jingrow.boot.developer_mode);
		frm.trigger("event");
	},
	document_type: function (frm) {
		jingrow.notification.setup_fieldname_select(frm);
	},
	view_properties: function (frm) {
		jingrow.route_options = { pg_type: frm.pg.document_type };
		jingrow.set_route("Form", "Customize Form");
	},
	event: function (frm) {
		if (!DATE_BASED_EVENTS.includes(frm.pg.event) || frm.is_new()) return;

		frm.add_custom_button(__("Get Alerts for Today"), function () {
			jingrow.call({
				method: "jingrow.email.pagetype.notification.notification.get_documents_for_today",
				args: {
					notification: frm.pg.name,
				},
				callback: function (r) {
					if (r.message && r.message.length > 0) {
						jingrow.msgprint(r.message.toString());
					} else {
						jingrow.msgprint(__("No alerts for today"));
					}
				},
			});
		});
	},
	channel: function (frm) {
		frm.toggle_reqd("recipients", frm.pg.channel == "Email");
		jingrow.notification.setup_fieldname_select(frm);
		jingrow.notification.setup_example_message(frm);
		if (frm.pg.channel === "SMS" && frm.pg.__islocal) {
			frm.set_df_property(
				"channel",
				"description",
				`To use SMS Channel, initialize <a href="/app/sms-settings">SMS Settings</a>.`
			);
		} else {
			frm.set_df_property("channel", "description", ` `);
		}
	},
});
