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

import json

import influxframework

# import influxframework
from influxframework.model.document import Document


class DashboardSettings(Document):
	pass


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


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

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


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

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

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