import jingrow

# this is a separate file since it is imported in jingrow.model.page
# to avoid circular imports

EVENT_MAP = {
	"before_insert": "Before Insert",
	"after_insert": "After Insert",
	"before_validate": "Before Validate",
	"validate": "Before Save",
	"on_update": "After Save",
	"before_rename": "Before Rename",
	"after_rename": "After Rename",
	"before_submit": "Before Submit",
	"on_submit": "After Submit",
	"before_cancel": "Before Cancel",
	"on_cancel": "After Cancel",
	"on_trash": "Before Delete",
	"after_delete": "After Delete",
	"before_update_after_submit": "Before Save (Submitted Page)",
	"on_update_after_submit": "After Save (Submitted Page)",
	"before_print": "Before Print",
	"on_payment_authorized": "On Payment Authorization",
}


def run_server_script_for_pg_event(pg, event):
	# run document event method
	if event not in EVENT_MAP:
		return

	if jingrow.flags.in_install:
		return

	if jingrow.flags.in_migrate:
		return

	scripts = get_server_script_map().get(pg.pagetype, {}).get(EVENT_MAP[event], None)
	if scripts:
		# run all scripts for this pagetype + event
		for script_name in scripts:
			jingrow.get_pg("Server Script", script_name).execute_pg(pg)


def get_server_script_map():
	# fetch cached server script methods
	# {
	# 	'[pagetype]': {
	# 		'Before Insert': ['[server script 1]', '[server script 2]']
	# 	},
	# 	'_api': {
	# 		'[path]': '[server script]'
	# 	},
	# 	'permission_query': {
	# 		'PageType': '[server script]'
	# 	}
	# }
	if jingrow.flags.in_patch and not jingrow.db.table_exists("Server Script"):
		return {}

	script_map = jingrow.cache.get_value("server_script_map")
	if script_map is None:
		script_map = {"permission_query": {}}
		enabled_server_scripts = jingrow.get_all(
			"Server Script",
			fields=("name", "reference_pagetype", "pagetype_event", "api_method", "script_type"),
			filters={"disabled": 0},
		)
		for script in enabled_server_scripts:
			if script.script_type == "PageType Event":
				script_map.setdefault(script.reference_pagetype, {}).setdefault(
					script.pagetype_event, []
				).append(script.name)
			elif script.script_type == "Permission Query":
				script_map["permission_query"][script.reference_pagetype] = script.name
			else:
				script_map.setdefault("_api", {})[script.api_method] = script.name

		jingrow.cache.set_value("server_script_map", script_map)

	return script_map
