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

import json

import influxframework
from influxframework import _
from influxframework.model.document import Document


class SessionDefaultSettings(Document):
	pass


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


@influxframework.whitelist()
def set_session_default_values(default_values):
	default_values = influxframework.parse_json(default_values)
	for entry in default_values:
		try:
			influxframework.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 = influxframework.get_single("Session Default Settings").session_defaults
	for entry in settings:
		influxframework.defaults.clear_user_default(influxframework.scrub(entry.ref_doctype))
