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

jingrow.ui.form.on("Print Format", "onload", function (frm) {
	frm.add_fetch("pg_type", "module", "module");
});

jingrow.ui.form.on("Print Format", {
	refresh: function (frm) {
		frm.set_intro("");
		frm.toggle_enable(["html", "pg_type", "module"], false);
		if (jingrow.session.user === "Administrator" || frm.pg.standard === "No") {
			frm.toggle_enable(["html", "pg_type", "module"], true);
			frm.enable_save();
		}

		if (frm.pg.standard === "Yes" && jingrow.session.user !== "Administrator") {
			frm.set_intro(__("Please duplicate this to make changes"));
		}
		frm.trigger("render_buttons");
		frm.toggle_display("standard", jingrow.boot.developer_mode);
		frm.trigger("hide_absolute_value_field");
	},
	render_buttons: function (frm) {
		frm.page.clear_inner_toolbar();
		if (!frm.is_new()) {
			if (!frm.pg.custom_format) {
				frm.add_custom_button(__("Edit Format"), function () {
					if (!frm.pg.pg_type) {
						jingrow.msgprint(__("Please select PageType first"));
						return;
					}
					if (frm.pg.print_format_builder_beta) {
						jingrow.set_route("print-format-builder-beta", frm.pg.name);
					} else {
						jingrow.set_route("print-format-builder", frm.pg.name);
					}
				});
			} else if (frm.pg.custom_format && !frm.pg.raw_printing) {
				frm.set_df_property("html", "reqd", 1);
			}
			if (jingrow.model.can_write("Customize Form")) {
				jingrow.model.with_pagetype(frm.pg.pg_type, function () {
					let current_format = jingrow.get_meta(frm.pg.pg_type).default_print_format;
					if (current_format == frm.pg.name) {
						return;
					}

					frm.add_custom_button(__("Set as Default"), function () {
						jingrow.call({
							method: "jingrow.printing.pagetype.print_format.print_format.make_default",
							args: {
								name: frm.pg.name,
							},
							callback: function () {
								frm.refresh();
							},
						});
					});
				});
			}
		}
	},
	custom_format: function (frm) {
		var value = frm.pg.custom_format ? 0 : 1;
		frm.set_value("align_labels_right", value);
		frm.set_value("show_section_headings", value);
		frm.set_value("line_breaks", value);
		frm.trigger("render_buttons");
	},
	pg_type: function (frm) {
		frm.trigger("hide_absolute_value_field");
	},
	hide_absolute_value_field: function (frm) {
		// TODO: make it work with frm.pg.pg_type
		// Problem: frm isn't updated in some random cases
		const pagetype = locals[frm.pg.pagetype][frm.pg.name].pg_type;
		if (pagetype) {
			jingrow.model.with_pagetype(pagetype, () => {
				const meta = jingrow.get_meta(pagetype);
				const has_int_float_currency_field = meta.fields.filter((df) =>
					["Int", "Float", "Currency"].includes(df.fieldtype)
				);
				frm.toggle_display("absolute_value", has_int_float_currency_field.length);
			});
		}
	},
});
