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

jingrow.ui.form.on("Form Tour", {
	refresh(frm) {
		if (frm.pg.is_standard && !jingrow.boot.developer_mode) {
			frm.trigger("disable_form");
		}
		frm.set_query("reference_pagetype", () => {
			return { filters: { istable: 0 } };
		});
		frm.trigger("reference_pagetype");
		frm.set_query("report_name", () => {
			if (frm.pg.reference_pagetype) {
				return {
					filters: {
						ref_pagetype: frm.pg.reference_pagetype,
					},
				};
			}
			return {};
		});
		!frm.is_new() && add_custom_button(frm);
	},
	async report_name(frm) {
		if (!frm.pg.ui_tour || !frm.pg.report_name) return;
		let { message } = await jingrow.db.get_value("Report", frm.pg.report_name, "ref_pagetype");
		frm.set_value("reference_pagetype", message?.ref_pagetype || "");
	},
	async before_save(frm) {
		if (
			frm.pg.select_view == "List" &&
			frm.pg.list_name == "Dashboard" &&
			frm.pg.dashboard_name &&
			frm.pg.reference_pagetype
		) {
			jingrow.throw(
				__("Referance Pagetype and Dashboard Name both can't be used at the same time.")
			);
		}
		frm.pg.ui_tour && (frm.pg.page_route = JSON.stringify(await get_path(frm)));
	},
	disable_form: function (frm) {
		frm.set_read_only();
		frm.fields
			.filter((field) => field.has_input)
			.forEach((field) => {
				frm.set_df_property(field.df.fieldname, "read_only", "1");
			});
		frm.disable_save();
	},

	reference_pagetype(frm) {
		if (!frm.pg.reference_pagetype) return;

		frm.set_fields_as_options("fieldname", frm.pg.reference_pagetype, (df) => !df.hidden).then(
			(options) => {
				frm.fields_dict.steps.grid.update_pagefield_property(
					"fieldname",
					"options",
					[""].concat(options)
				);
			}
		);

		frm.set_fields_as_options(
			"parent_fieldname",
			frm.pg.reference_pagetype,
			(df) => df.fieldtype == "Table" && !df.hidden
		).then((options) => {
			frm.fields_dict.steps.grid.update_pagefield_property(
				"parent_fieldname",
				"options",
				[""].concat(options)
			);
		});
		if (!frm.pg.ui_tour) {
			// remove report name if reference pagetype is changed and report name is not valid.
			jingrow.db
				.get_list(
					"Report",
					{
						filters: {
							ref_pagetype: frm.pg.reference_pagetype,
						},
					},
					{ fields: ["name"] }
				)
				.then((reports) => {
					if (reports.findIndex((r) => r.name == frm.pg.report_name) == -1) {
						frm.set_value("report_name", "");
						frm.refresh_field("report_name");
					}
				});
		}
	},
});

let add_custom_button = (frm) => {
	if (frm.pg.ui_tour) {
		frm.add_custom_button(__("Reset"), function () {
			jingrow.confirm(
				__("This will reset this tour and show it to all users. Are you sure?"),
				function () {
					jingrow.call({
						method: "jingrow.desk.pagetype.form_tour.form_tour.reset_tour",
						args: {
							tour_name: frm.pg.name,
						},
					});
					delete jingrow.boot.user.onboarding_status[frm.pg.name];
				}
			);
		});
	} else {
		frm.add_custom_button(__("Show Tour"), async () => {
			const issingle = await check_if_single(frm.pg.reference_pagetype);
			let route_changed = null;

			if (issingle) {
				route_changed = jingrow.set_route("Form", frm.pg.reference_pagetype);
			} else if (frm.pg.first_document) {
				const name = await get_first_document(frm.pg.reference_pagetype);
				route_changed = jingrow.set_route("Form", frm.pg.reference_pagetype, name);
			} else {
				route_changed = jingrow.set_route("Form", frm.pg.reference_pagetype, "new");
			}
			route_changed.then(() => {
				const tour_name = frm.pg.name;
				cur_frm.tour.init({ tour_name }).then(() => cur_frm.tour.start());
			});
		});
	}
};

jingrow.ui.form.on("Form Tour Step", {
	form_render(frm, cdt, cdn) {
		if (locals[cdt][cdn].is_table_field) {
			frm.trigger("parent_fieldname", cdt, cdn);
		}
	},
	parent_fieldname(frm, cdt, cdn) {
		const child_row = locals[cdt][cdn];

		const parent_fieldname_df = jingrow
			.get_meta(frm.pg.reference_pagetype)
			.fields.find((df) => df.fieldname == child_row.parent_fieldname);

		frm.set_fields_as_options(
			"fieldname",
			parent_fieldname_df.options,
			(df) => !df.hidden
		).then((options) => {
			frm.fields_dict.steps.grid.update_pagefield_property(
				"fieldname",
				"options",
				[""].concat(options)
			);
			if (child_row.fieldname) {
				jingrow.model.set_value(cdt, cdn, "fieldname", child_row.fieldname);
			}
		});
	},
});

async function check_if_single(pagetype) {
	const { message } = await jingrow.db.get_value("PageType", pagetype, "issingle");
	return message.issingle || 0;
}
async function check_if_private_workspace(name) {
	const { message } = await jingrow.db.get_value("Workspace", name, "public");
	return !message.public || 0;
}

async function get_first_document(pagetype) {
	let pagename;

	await jingrow.db.get_list(pagetype, { order_by: "creation" }).then((res) => {
		if (Array.isArray(res) && res.length) pagename = res[0].name;
	});

	return pagename || "new";
}

async function get_path(frm) {
	let route = [frm.pg.view_name];
	switch (route[0]) {
		case "Workspaces":
			frm.pg.list_name = "";
			frm.pg.new_document_form = 0;
			frm.pg.report_name = "";
			frm.pg.page_name = "";
			frm.pg.dashboard_name = "";
			frm.pg.reference_pagetype = "";
			if (!frm.pg.workspace_name) {
				route.push("*");
				return route;
			}
			if (await check_if_private_workspace(frm.pg.workspace_name)) {
				route.push("private");
			}
			route.push(frm.pg.workspace_name);
			return route;
		case "List":
			frm.pg.workspace_name = "";
			frm.pg.new_document_form = 0;
			frm.pg.list_name != "Report" && (frm.pg.report_name = "");
			frm.pg.list_name != "Dashboard" && (frm.pg.dashboard_name = "");
			frm.pg.page_name = "";
			if (frm.pg.list_name == "File") return ["List", "File"];
			if (!frm.pg.reference_pagetype) {
				if (frm.pg.list_name == "Dashboard")
					return ["dashboard-view", frm.pg.dashboard_name || "*"];
				route.push("*");
			} else {
				route.push(frm.pg.reference_pagetype);
			}
			route.push(frm.pg.list_name);
			return route;
		case "Form":
			frm.pg.workspace_name = "";
			frm.pg.list_name = "";
			frm.pg.report_name = "";
			frm.pg.page_name = "";
			frm.pg.dashboard_name = "";
			if (!frm.pg.reference_pagetype) {
				route.push("*");
				frm.pg.new_document_form && route.push("new-*");
				return route;
			}
			route.push(frm.pg.reference_pagetype);
			if (await check_if_single(frm.pg.reference_pagetype)) {
				route.push(frm.pg.reference_pagetype);
			} else if (frm.pg.new_document_form) {
				route.push("new-" + jingrow.router.slug(frm.pg.reference_pagetype));
			}
			return route;
		case "Tree":
			frm.pg.workspace_name = "";
			frm.pg.list_name = "";
			frm.pg.new_document_form = 0;
			frm.pg.report_name = "";
			frm.pg.page_name = "";
			frm.pg.dashboard_name = "";
			return route;
		case "Page":
			frm.pg.workspace_name = "";
			frm.pg.list_name = "";
			frm.pg.new_document_form = 0;
			frm.pg.report_name = "";
			frm.pg.dashboard_name = "";
			frm.pg.reference_pagetype = "";
			return [frm.pg.page_name];
	}
}
