jingrow.ui.form.on("Communication", {
	onload: function (frm) {
		if (frm.pg.content) {
			frm.pg.content = jingrow.dom.remove_script_and_style(frm.pg.content);
		}
		frm.set_query("reference_pagetype", function () {
			return {
				filters: {
					issingle: 0,
					istable: 0,
				},
			};
		});
	},
	refresh: function (frm) {
		if (frm.is_new()) return;

		frm.convert_to_click && frm.set_convert_button();
		frm.subject_field = "subject";

		// content field contains weird table html that does not render well in Quill
		// this field is not to be edited directly anyway, so setting it as read only
		frm.set_df_property("content", "read_only", 1);

		if (frm.pg.reference_pagetype && frm.pg.reference_name) {
			frm.add_custom_button(__(frm.pg.reference_name), function () {
				jingrow.set_route("Form", frm.pg.reference_pagetype, frm.pg.reference_name);
			});
		} else {
			// if an unlinked communication, set email field
			if (frm.pg.sent_or_received === "Received") {
				frm.email_field = "sender";
			} else {
				frm.email_field = "recipients";
			}
		}

		if (frm.pg.status === "Open") {
			frm.add_custom_button(__("Close"), function () {
				frm.trigger("mark_as_closed_open");
			});
		} else if (frm.pg.status !== "Linked") {
			frm.add_custom_button(__("Reopen"), function () {
				frm.trigger("mark_as_closed_open");
			});
		}

		frm.add_custom_button(__("Relink"), function () {
			frm.trigger("show_relink_dialog");
		});

		if (
			frm.pg.communication_type == "Communication" &&
			frm.pg.communication_medium == "Email" &&
			frm.pg.sent_or_received == "Received"
		) {
			frm.add_custom_button(__("Reply"), function () {
				frm.trigger("reply");
			});

			frm.add_custom_button(
				__("Reply All"),
				function () {
					frm.trigger("reply_all");
				},
				__("Actions")
			);

			frm.add_custom_button(
				__("Forward"),
				function () {
					frm.trigger("forward_mail");
				},
				__("Actions")
			);

			frm.add_custom_button(
				frm.pg.seen ? __("Mark as Unread") : __("Mark as Read"),
				function () {
					frm.trigger("mark_as_read_unread");
				},
				__("Actions")
			);

			frm.add_custom_button(
				__("Move"),
				function () {
					frm.trigger("show_move_dialog");
				},
				__("Actions")
			);

			if (frm.pg.email_status != "Spam")
				frm.add_custom_button(
					__("Mark as Spam"),
					function () {
						frm.trigger("mark_as_spam");
					},
					__("Actions")
				);

			if (frm.pg.email_status != "Trash") {
				frm.add_custom_button(
					__("Move To Trash"),
					function () {
						frm.trigger("move_to_trash");
					},
					__("Actions")
				);
			}

			frm.add_custom_button(
				__("Contact"),
				function () {
					frm.trigger("add_to_contact");
				},
				__("Create")
			);
		}

		if (
			frm.pg.communication_type == "Communication" &&
			frm.pg.communication_medium == "Phone" &&
			frm.pg.sent_or_received == "Received"
		) {
			frm.add_custom_button(
				__("Add Contact"),
				function () {
					frm.trigger("add_to_contact");
				},
				__("Actions")
			);
		}
	},

	show_relink_dialog: function (frm) {
		var d = new jingrow.ui.Dialog({
			title: __("Relink Communication"),
			fields: [
				{
					fieldtype: "Link",
					options: "PageType",
					label: __("Reference Pagetype"),
					fieldname: "reference_pagetype",
					get_query: function () {
						return { query: "jingrow.email.get_communication_pagetype" };
					},
				},
				{
					fieldtype: "Dynamic Link",
					options: "reference_pagetype",
					label: __("Reference Name"),
					fieldname: "reference_name",
				},
			],
		});
		d.set_value("reference_pagetype", frm.pg.reference_pagetype);
		d.set_value("reference_name", frm.pg.reference_name);
		d.set_primary_action(__("Relink"), function () {
			var values = d.get_values();
			if (values) {
				jingrow.confirm(
					__("Are you sure you want to relink this communication to {0}?", [
						values["reference_name"],
					]),
					function () {
						d.hide();
						jingrow.call({
							method: "jingrow.email.relink",
							args: {
								name: frm.pg.name,
								reference_pagetype: values["reference_pagetype"],
								reference_name: values["reference_name"],
							},
							callback: function () {
								frm.refresh();
							},
						});
					},
					function () {
						jingrow.show_alert({
							message: __("Document not Relinked"),
							indicator: "info",
						});
					}
				);
			}
		});
		d.show();
	},

	show_move_dialog: function (frm) {
		var d = new jingrow.ui.Dialog({
			title: __("Move"),
			fields: [
				{
					fieldtype: "Link",
					options: "Email Account",
					label: __("Email Account"),
					fieldname: "email_account",
					reqd: 1,
					get_query: function () {
						return {
							filters: {
								name: ["!=", frm.pg.email_account],
								enable_incoming: ["=", 1],
							},
						};
					},
				},
			],
			primary_action_label: __("Move"),
			primary_action(values) {
				d.hide();
				jingrow.call({
					method: "jingrow.email.inbox.move_email",
					args: {
						communication: frm.pg.name,
						email_account: values.email_account,
					},
					freeze: true,
					callback: function () {
						window.history.back();
					},
				});
			},
		});
		d.show();
	},

	mark_as_read_unread: function (frm) {
		var action = frm.pg.seen ? "Unread" : "Read";
		var flag = "(\\SEEN)";

		return jingrow.call({
			method: "jingrow.email.inbox.create_email_flag_queue",
			args: {
				names: [frm.pg.name],
				action: action,
				flag: flag,
			},
			freeze: true,
			callback: function () {
				frm.reload_pg();
			},
		});
	},

	mark_as_closed_open: function (frm) {
		var status = frm.pg.status == "Open" ? "Closed" : "Open";

		return jingrow.call({
			method: "jingrow.email.inbox.mark_as_closed_open",
			args: {
				communication: frm.pg.name,
				status: status,
			},
			freeze: true,
			callback: function () {
				frm.reload_pg();
			},
		});
	},

	reply: function (frm) {
		var args = frm.events.get_mail_args(frm);
		$.extend(args, {
			subject: __("Re: {0}", [frm.pg.subject]),
			recipients: frm.pg.sender,
			is_a_reply: true,
		});

		new jingrow.views.CommunicationComposer(args);
	},

	reply_all: function (frm) {
		var args = frm.events.get_mail_args(frm);
		$.extend(args, {
			subject: __("Res: {0}", [frm.pg.subject]),
			recipients: frm.pg.sender,
			cc: frm.pg.cc,
			is_a_reply: true,
		});
		new jingrow.views.CommunicationComposer(args);
	},

	forward_mail: function (frm) {
		var args = frm.events.get_mail_args(frm);
		$.extend(args, {
			forward: true,
			subject: __("Fw: {0}", [frm.pg.subject]),
			is_a_reply: true,
		});

		new jingrow.views.CommunicationComposer(args);
	},

	get_mail_args: function (frm) {
		var sender_email_id = "";
		$.each(jingrow.boot.email_accounts, function (idx, account) {
			if (account.email_account == frm.pg.email_account) {
				sender_email_id = account.email_id;
				return;
			}
		});

		return {
			frm: frm,
			pg: frm.pg,
			last_email: frm.pg,
			sender: sender_email_id,
			attachments: frm.pg.attachments,
		};
	},

	add_to_contact: function (frm) {
		var me = this;
		var fullname = frm.pg.sender_full_name || "";

		var names = fullname.split(" ");
		var first_name = names[0];
		var last_name = names.length >= 2 ? names[names.length - 1] : "";

		jingrow.route_options = {
			email_id: frm.pg.sender || "",
			first_name: first_name,
			last_name: last_name,
			mobile_no: frm.pg.phone_no || "",
		};
		jingrow.new_pg("Contact");
	},

	mark_as_spam: function (frm) {
		jingrow.call({
			method: "jingrow.email.inbox.mark_as_spam",
			args: {
				communication: frm.pg.name,
				sender: frm.pg.sender,
			},
			freeze: true,
			callback: function (r) {
				jingrow.msgprint(__("Email has been marked as spam"));
			},
		});
	},

	move_to_trash: function (frm) {
		jingrow.call({
			method: "jingrow.email.inbox.mark_as_trash",
			args: {
				communication: frm.pg.name,
			},
			freeze: true,
			callback: function (r) {
				jingrow.msgprint(__("Email has been moved to trash"));
			},
		});
	},
});
