jingrow.provide("jingrow.contacts");

$.extend(jingrow.contacts, {
	clear_address_and_contact: function (frm) {
		$(frm.fields_dict["address_html"].wrapper).html("");
		frm.fields_dict["contact_html"] && $(frm.fields_dict["contact_html"].wrapper).html("");
	},

	render_address_and_contact: function (frm) {
		// render address
		if (frm.fields_dict["address_html"] && "addr_list" in frm.pg.__onload) {
			$(frm.fields_dict["address_html"].wrapper)
				.html(jingrow.render_template("address_list", frm.pg.__onload))
				.find(".btn-address")
				.on("click", () => new_record("Address", frm.pg));
		}

		// render contact
		if (frm.fields_dict["contact_html"] && "contact_list" in frm.pg.__onload) {
			$(frm.fields_dict["contact_html"].wrapper)
				.html(jingrow.render_template("contact_list", frm.pg.__onload))
				.find(".btn-contact")
				.on("click", () => new_record("Contact", frm.pg));
		}
	},
	get_last_pg: function (frm) {
		const reverse_routes = jingrow.route_history.slice().reverse();
		const last_route = reverse_routes.find((route) => {
			return route[0] === "Form" && route[1] !== frm.pagetype;
		});
		let pagetype = last_route && last_route[1];
		let pagename = last_route && last_route[2];

		if (last_route && last_route.length > 3) pagename = last_route.slice(2).join("/");

		return {
			pagetype,
			pagename,
		};
	},
	get_address_display: function (frm, address_field, display_field) {
		if (frm.updating_party_details) {
			return;
		}

		let _address_field = address_field || "address";
		let _display_field = display_field || "address_display";

		if (!frm.pg[_address_field]) {
			frm.set_value(_display_field, "");
			return;
		}

		jingrow
			.xcall("jingrow.contacts.pagetype.address.address.get_address_display", {
				address_dict: frm.pg[_address_field],
			})
			.then((address_display) => frm.set_value(_display_field, address_display));
	},
});

function new_record(pagetype, source_pg) {
	jingrow.dynamic_link = {
		pagetype: source_pg.pagetype,
		pg: source_pg,
		fieldname: "name",
	};

	return jingrow.new_pg(pagetype);
}
