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

jingrow.ui.form.on("Address", {
	refresh: function (frm) {
		if (frm.pg.__islocal) {
			const last_pg = jingrow.contacts.get_last_pg(frm);
			if (
				jingrow.dynamic_link &&
				jingrow.dynamic_link.pg &&
				jingrow.dynamic_link.pg.name == last_pg.pagename
			) {
				frm.set_value("links", "");
				frm.add_child("links", {
					link_pagetype: jingrow.dynamic_link.pagetype,
					link_name: jingrow.dynamic_link.pg[jingrow.dynamic_link.fieldname],
				});
			}
		}
		frm.set_query("link_pagetype", "links", function () {
			return {
				query: "jingrow.contacts.address_and_contact.filter_dynamic_link_pagetypes",
				filters: {
					fieldtype: "HTML",
					fieldname: "address_html",
				},
			};
		});
		frm.refresh_field("links");

		if (frm.pg.links) {
			for (let i in frm.pg.links) {
				let link = frm.pg.links[i];
				frm.add_custom_button(
					__("{0}: {1}", [__(link.link_pagetype), __(link.link_name)]),
					function () {
						jingrow.set_route("Form", link.link_pagetype, link.link_name);
					},
					__("Links")
				);
			}
		}
	},
	validate: function (frm) {
		// clear linked customer / supplier / sales partner on saving...
		if (frm.pg.links) {
			frm.pg.links.forEach(function (d) {
				jingrow.model.remove_from_locals(d.link_pagetype, d.link_name);
			});
		}
	},
	after_save: function (frm) {
		jingrow.run_serially([
			() => jingrow.timeout(1),
			() => {
				const last_pg = jingrow.contacts.get_last_pg(frm);
				if (
					jingrow.dynamic_link &&
					jingrow.dynamic_link.pg &&
					jingrow.dynamic_link.pg.name == last_pg.pagename
				) {
					for (let i in frm.pg.links) {
						let link = frm.pg.links[i];
						if (
							last_pg.pagetype == link.link_pagetype &&
							last_pg.pagename == link.link_name
						) {
							jingrow.set_route("Form", last_pg.pagetype, last_pg.pagename);
						}
					}
				}
			},
		]);
	},
});
