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

jingrow.ui.form.on("Notification Log", {
	refresh: function (frm) {
		if (frm.pg.attached_file) {
			frm.trigger("set_attachment");
		} else {
			frm.get_field("attachment_link").$wrapper.empty();
		}
	},

	open_reference_document: function (frm) {
		if (frm.pg?.link) {
			jingrow.set_route(frm.pg.link);
			return;
		}
		const dt = frm.pg.document_type;
		const dn = frm.pg.document_name;
		jingrow.set_route("Form", dt, dn);
	},

	set_attachment: function (frm) {
		const attachment = JSON.parse(frm.pg.attached_file);

		const $wrapper = frm.get_field("attachment_link").$wrapper;
		$wrapper.html(`
			<div class="attached-file text-medium">
				<div class="ellipsis">
					<i class="fa fa-paperclip"></i>
					<a class="attached-file-link">${attachment.name}.pdf</a>
				</div>
			</div>
		`);

		$wrapper.find(".attached-file-link").click(() => {
			const w = window.open(
				jingrow.urllib.get_full_url(`/api/action/jingrow.utils.print_format.download_pdf?
					pagetype=${encodeURIComponent(attachment.pagetype)}
					&name=${encodeURIComponent(attachment.name)}
					&format=${encodeURIComponent(attachment.print_format)}
					&lang=${encodeURIComponent(attachment.lang)}`)
			);
			if (!w) {
				jingrow.msgprint(__("Please enable pop-ups"));
			}
		});
	},
});
