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

import json

import jingrow

# import jingrow
from jingrow.model.page import Page


class DashboardSettings(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.types import DF

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


@jingrow.whitelist()
def create_dashboard_settings(user):
	if not jingrow.db.exists("Dashboard Settings", user):
		pg = jingrow.new_pg("Dashboard Settings")
		pg.name = user
		pg.insert(ignore_permissions=True)
		jingrow.db.commit()
		return pg
	return jingrow.get_pg("Dashboard Settings", user)


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

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


@jingrow.whitelist()
def save_chart_config(reset, config, chart_name):
	reset = jingrow.parse_json(reset)
	pg = create_dashboard_settings(jingrow.session.user)
	chart_config = jingrow.parse_json(pg.chart_config) or {}

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

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