// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt

jingrow.breadcrumbs = {
	all: {},

	preferred: {
		File: "",
		Dashboard: "Customization",
		"Dashboard Chart": "Customization",
		"Dashboard Chart Source": "Customization",
	},

	module_map: {
		Core: "Settings",
		Email: "Settings",
		Custom: "Settings",
		Workflow: "Settings",
		Printing: "Settings",
		Setup: "Settings",
		Automation: "Tools",
	},

	set_pagetype_module(pagetype, module) {
		localStorage["preferred_breadcrumbs:" + pagetype] = module;
	},

	get_pagetype_module(pagetype) {
		return localStorage["preferred_breadcrumbs:" + pagetype];
	},

	add(module, pagetype, type) {
		let obj;
		if (typeof module === "object") {
			obj = module;
		} else {
			obj = {
				module: module,
				pagetype: pagetype,
				type: type,
			};
		}
		this.all[jingrow.breadcrumbs.current_page()] = obj;
		this.update();
	},

	current_page() {
		return jingrow.get_route_str();
	},

	update() {
		var breadcrumbs = this.all[jingrow.breadcrumbs.current_page()];

		this.clear();
		if (!breadcrumbs) return this.toggle(false);

		if (breadcrumbs.type === "Custom") {
			this.set_custom_breadcrumbs(breadcrumbs);
		} else {
			// workspace
			this.set_workspace_breadcrumb(breadcrumbs);

			// form / print
			let view = jingrow.get_route()[0];
			view = view ? view.toLowerCase() : null;
			if (breadcrumbs.pagetype && ["print", "form"].includes(view)) {
				this.set_list_breadcrumb(breadcrumbs);
				this.set_form_breadcrumb(breadcrumbs, view);
			} else if (breadcrumbs.pagetype && view === "list") {
				this.set_list_breadcrumb(breadcrumbs);
			} else if (breadcrumbs.pagetype && view == "dashboard-view") {
				this.set_list_breadcrumb(breadcrumbs);
				this.set_dashboard_breadcrumb(breadcrumbs);
			}
		}

		this.toggle(true);
	},

	set_custom_breadcrumbs(breadcrumbs) {
		this.append_breadcrumb_element(breadcrumbs.route, breadcrumbs.label);
	},

	append_breadcrumb_element(route, label) {
		const el = document.createElement("li");
		const a = document.createElement("a");
		a.href = route;
		a.innerText = label;
		el.appendChild(a);
		this.$breadcrumbs.append(el);
	},

	get last_route() {
		return jingrow.route_history.slice(-2)[0];
	},

	set_workspace_breadcrumb(breadcrumbs) {
		// get preferred module for breadcrumbs, based on history and module

		if (!breadcrumbs.workspace) {
			this.set_workspace(breadcrumbs);
		}

		if (!breadcrumbs.workspace) {
			return;
		}

		if (
			breadcrumbs.module_info &&
			(breadcrumbs.module_info.blocked ||
				!jingrow.visible_modules.includes(breadcrumbs.module_info.module))
		) {
			return;
		}

		this.append_breadcrumb_element(
			`/app/${jingrow.router.slug(breadcrumbs.workspace)}`,
			__(breadcrumbs.workspace)
		);
	},

	set_workspace(breadcrumbs) {
		// try and get module from pagetype or other settings
		// then get the workspace for that module

		this.setup_modules();
		var from_module = this.get_pagetype_module(breadcrumbs.pagetype);

		if (from_module) {
			breadcrumbs.module = from_module;
		} else if (this.preferred[breadcrumbs.pagetype] !== undefined) {
			// get preferred module for breadcrumbs
			breadcrumbs.module = this.preferred[breadcrumbs.pagetype];
		}

		// guess from last route
		if (this.last_route?.[0] == "Workspaces") {
			let last_workspace = this.last_route[1];

			if (
				breadcrumbs.module &&
				jingrow.boot.module_wise_workspaces[breadcrumbs.module]?.includes(last_workspace)
			) {
				breadcrumbs.workspace = last_workspace;
				return;
			}
		}

		if (breadcrumbs.module) {
			if (this.module_map[breadcrumbs.module]) {
				breadcrumbs.module = this.module_map[breadcrumbs.module];
			}

			breadcrumbs.module_info = jingrow.get_module(breadcrumbs.module);

			// set workspace
			if (
				breadcrumbs.module_info &&
				jingrow.boot.module_wise_workspaces[breadcrumbs.module]
			) {
				breadcrumbs.workspace = jingrow.boot.module_wise_workspaces[breadcrumbs.module][0];
			}
		}
	},

	set_list_breadcrumb(breadcrumbs) {
		const pagetype = breadcrumbs.pagetype;
		const pagetype_meta = jingrow.get_pg("PageType", pagetype);
		if (
			(pagetype === "User" && !jingrow.user.has_role("System Manager")) ||
			pagetype_meta?.issingle
		) {
			// no user listview for non-system managers and single pagetypes
		} else {
			let route;
			const pagetype_route = jingrow.router.slug(jingrow.router.pagetype_layout || pagetype);
			if (pagetype_meta?.is_tree) {
				let view = jingrow.model.user_settings[pagetype].last_view || "Tree";
				route = `${pagetype_route}/view/${view}`;
			} else {
				route = pagetype_route;
			}
			this.append_breadcrumb_element(`/app/${route}`, __(pagetype));
		}
	},

	set_form_breadcrumb(breadcrumbs, view) {
		const pagetype = breadcrumbs.pagetype;
		let pagename = jingrow.get_route().slice(2).join("/");
		let pagename_title;
		if (pagename.startsWith("new-" + pagetype.toLowerCase().replace(/ /g, "-"))) {
			pagename_title = __("New {0}", [__(pagetype)]);
		} else {
			pagename_title = __(pagename);
		}
		let form_route = `/app/${jingrow.router.slug(pagetype)}/${encodeURIComponent(pagename)}`;
		this.append_breadcrumb_element(form_route, pagename_title);

		if (view === "form") {
			let last_crumb = this.$breadcrumbs.find("li").last();
			last_crumb.addClass("disabled");
			last_crumb.css("cursor", "copy");
			last_crumb.click((event) => {
				event.stopImmediatePropagation();
				jingrow.utils.copy_to_clipboard(last_crumb.text());
			});
		}
	},

	set_dashboard_breadcrumb(breadcrumbs) {
		const pagetype = breadcrumbs.pagetype;
		const pagename = jingrow.get_route()[1];
		let dashboard_route = `/app/${jingrow.router.slug(pagetype)}/${pagename}`;
		$(`<li><a href="${dashboard_route}">${__(pagename)}</a></li>`).appendTo(this.$breadcrumbs);
	},

	setup_modules() {
		if (!jingrow.visible_modules) {
			jingrow.visible_modules = $.map(jingrow.boot.allowed_workspaces, (m) => {
				return m.module;
			});
		}
	},

	rename(pagetype, old_name, new_name) {
		var old_route_str = ["Form", pagetype, old_name].join("/");
		var new_route_str = ["Form", pagetype, new_name].join("/");
		this.all[new_route_str] = this.all[old_route_str];
		delete jingrow.breadcrumbs.all[old_route_str];
		this.update();
	},

	clear() {
		this.$breadcrumbs = $("#navbar-breadcrumbs").empty();
	},

	toggle(show) {
		if (show) {
			$("body").addClass("no-breadcrumbs");
		} else {
			$("body").removeClass("no-breadcrumbs");
		}
	},
};
