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

jingrow.ui.form.States = class FormStates {
	constructor(opts) {
		$.extend(this, opts);
		this.state_fieldname = jingrow.workflow.get_state_fieldname(this.frm.pagetype);

		// no workflow?
		if (!this.state_fieldname) return;

		this.update_fields = jingrow.workflow.get_update_fields(this.frm.pagetype);

		var me = this;
		$(this.frm.wrapper).bind("render_complete", function () {
			me.refresh();
		});
	}

	setup_help() {
		var me = this;
		this.frm.page.add_action_item(
			__("Help"),
			function () {
				jingrow.workflow.setup(me.frm.pagetype);
				var state = me.get_state();
				var d = new jingrow.ui.Dialog({
					title: "Workflow: " + jingrow.workflow.workflows[me.frm.pagetype].name,
				});

				jingrow.workflow.get_transitions(me.frm.pg).then((transitions) => {
					const next_actions =
						$.map(
							transitions,
							(d) => `${d.action.bold()} ${__("by Role")} ${d.allowed}`
						).join(", ") || __("None: End of Workflow").bold();

					const document_editable_by = jingrow.workflow
						.get_document_state_roles(me.frm.pagetype, state)
						.map((role) => role.bold())
						.join(", ");

					$(d.body)
						.html(
							`
					<p>${__("Current status")}: ${state.bold()}</p>
					<p>${__("Document is only editable by users with role")}: ${document_editable_by}</p>
					<p>${__("Next actions")}: ${next_actions}</p>
					<p>${__("{0}: Other permission rules may also apply", [__("Note").bold()])}</p>
				`
						)
						.css({ padding: "15px" });

					d.show();
				});
			},
			true
		);
	}

	refresh() {
		// hide if its not yet saved
		if (this.frm.pg.__islocal) {
			this.set_default_state();
			return;
		}

		// state text
		const state = this.get_state();

		if (state) {
			// show actions from that state
			this.show_actions(state);
		}
	}

	show_actions() {
		var added = false;
		var me = this;

		// if the loaded pg is dirty, don't show workflow buttons
		if (this.frm.pg.__unsaved === 1) {
			return;
		}

		function has_approval_access(transition) {
			let approval_access = false;
			const user = jingrow.session.user;
			if (
				user === "Administrator" ||
				transition.allow_self_approval ||
				user !== me.frm.pg.owner
			) {
				approval_access = true;
			}
			return approval_access;
		}

		jingrow.workflow.get_transitions(this.frm.pg).then((transitions) => {
			this.frm.page.clear_actions_menu();
			transitions.forEach((d) => {
				if (jingrow.user_roles.includes(d.allowed) && has_approval_access(d)) {
					added = true;
					me.frm.page.add_action_item(__(d.action), function () {
						// set the workflow_action for use in form scripts
						jingrow.dom.freeze();
						me.frm.selected_workflow_action = d.action;
						me.frm.script_manager.trigger("before_workflow_action").then(() => {
							jingrow
								.xcall("jingrow.model.workflow.apply_workflow", {
									pg: me.frm.pg,
									action: d.action,
								})
								.then((pg) => {
									jingrow.model.sync(pg);
									me.frm.refresh();
									me.frm.selected_workflow_action = null;
									me.frm.script_manager.trigger("after_workflow_action");
								})
								.finally(() => {
									jingrow.dom.unfreeze();
								});
						});
					});
				}
			});

			this.setup_btn(added);
		});
	}

	setup_btn(action_added) {
		if (action_added) {
			this.frm.page.btn_primary.addClass("hide");
			this.frm.page.btn_secondary.addClass("hide");
			this.frm.toolbar.current_status = "";
			this.setup_help();
		}
	}

	set_default_state() {
		var default_state = jingrow.workflow.get_default_state(
			this.frm.pagetype,
			this.frm.pg.pagestatus
		);
		if (default_state) {
			this.frm.set_value(this.state_fieldname, default_state);
		}
	}

	get_state() {
		if (!this.frm.pg[this.state_fieldname]) {
			this.set_default_state();
		}
		return this.frm.pg[this.state_fieldname];
	}
};
