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

import json

import influxframework
from influxframework.model.document import Document
from influxframework.utils.safe_exec import read_sql, safe_exec


class SystemConsole(Document):
	def run(self):
		influxframework.only_for("System Manager")
		try:
			influxframework.local.debug_log = []
			if self.type == "Python":
				safe_exec(self.console)
				self.output = "\n".join(influxframework.debug_log)
			elif self.type == "SQL":
				self.output = influxframework.as_json(read_sql(self.console, as_dict=1))
		except Exception:
			self.output = influxframework.get_traceback()

		if self.commit:
			influxframework.db.commit()
		else:
			influxframework.db.rollback()

		influxframework.get_doc(dict(doctype="Console Log", script=self.console, output=self.output)).insert()
		influxframework.db.commit()


@influxframework.whitelist()
def execute_code(doc):
	console = influxframework.get_doc(json.loads(doc))
	console.run()
	return console.as_dict()


@influxframework.whitelist()
def show_processlist():
	influxframework.only_for("System Manager")

	return influxframework.db.multisql(
		{
			"postgres": """
			SELECT pid AS "Id",
				query_start AS "Time",
				state AS "State",
				query AS "Info",
				wait_event AS "Progress"
			FROM pg_stat_activity""",
			"mariadb": "show full processlist",
		},
		as_dict=True,
	)
