# Copyright (c) 2019, JINGROW
# License: MIT. See LICENSE

import json

import jingrow
from jingrow import _
from jingrow.model.page import Page


class SessionDefaultSettings(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.core.pagetype.session_default.session_default import SessionDefault
		from jingrow.types import DF

		session_defaults: DF.Table[SessionDefault]
	# end: auto-generated types
	pass


@jingrow.whitelist()
def get_session_default_values():
	settings = jingrow.get_single("Session Default Settings")
	fields = []
	for default_values in settings.session_defaults:
		reference_pagetype = jingrow.scrub(default_values.ref_pagetype)
		fields.append(
			{
				"fieldname": reference_pagetype,
				"fieldtype": "Link",
				"options": default_values.ref_pagetype,
				"label": _("Default {0}").format(_(default_values.ref_pagetype)),
				"default": jingrow.defaults.get_user_default(reference_pagetype),
			}
		)
	return json.dumps(fields)


@jingrow.whitelist()
def set_session_default_values(default_values):
	default_values = jingrow.parse_json(default_values)
	for entry in default_values:
		try:
			jingrow.defaults.set_user_default(entry, default_values.get(entry))
		except Exception:
			return
	return "success"


# called on hook 'on_logout' to clear defaults for the session
def clear_session_defaults():
	settings = jingrow.get_single("Session Default Settings").session_defaults
	for entry in settings:
		jingrow.defaults.clear_user_default(jingrow.scrub(entry.ref_pagetype))
