# Copyright (c) 2020, XhiveFramework Technologies and contributors
# License: MIT. See LICENSE

import json

import xhiveframework

# import xhiveframework
from xhiveframework.model.document import Document


class DashboardSettings(Document):
	# 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 xhiveframework.types import DF

		chart_config: DF.Code | None
		user: DF.Link | None
	# end: auto-generated types
	pass


@xhiveframework.whitelist()
def create_dashboard_settings(user):
	if not xhiveframework.db.exists("Dashboard Settings", user):
		doc = xhiveframework.new_doc("Dashboard Settings")
		doc.name = user
		doc.insert(ignore_permissions=True)
		xhiveframework.db.commit()
		return doc


def get_permission_query_conditions(user):
	if not user:
		user = xhiveframework.session.user

	return f"""(`tabDashboard Settings`.name = {xhiveframework.db.escape(user)})"""


@xhiveframework.whitelist()
def save_chart_config(reset, config, chart_name):
	reset = xhiveframework.parse_json(reset)
	doc = xhiveframework.get_doc("Dashboard Settings", xhiveframework.session.user)
	chart_config = xhiveframework.parse_json(doc.chart_config) or {}

	if reset:
		chart_config[chart_name] = {}
	else:
		config = xhiveframework.parse_json(config)
		if chart_name not in chart_config:
			chart_config[chart_name] = {}
		chart_config[chart_name].update(config)

	xhiveframework.db.set_value("Dashboard Settings", xhiveframework.session.user, "chart_config", json.dumps(chart_config))
