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

import json

import jingrow
from jingrow.model.page import Page
from jingrow.utils.safe_exec import read_sql, safe_exec


class SystemConsole(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

		commit: DF.Check
		console: DF.Code | None
		output: DF.Code | None
		show_processlist: DF.Check
		type: DF.Literal["Python", "SQL"]

	# end: auto-generated types
	def run(self):
		jingrow.only_for("System Manager")
		try:
			jingrow.local.debug_log = []
			if self.type == "Python":
				safe_exec(self.console, script_filename="System Console")
				self.output = "\n".join(jingrow.debug_log)
			elif self.type == "SQL":
				self.output = jingrow.as_json(read_sql(self.console, as_dict=1))
		except Exception:
			self.commit = False
			self.output = jingrow.get_traceback()

		if self.commit:
			jingrow.db.commit()
		else:
			jingrow.db.rollback()
		jingrow.get_pg(
			dict(pagetype="Console Log", script=self.console, type=self.type, committed=self.commit)
		).insert()
		jingrow.db.commit()


@jingrow.whitelist()
def execute_code(pg):
	console = jingrow.get_pg(json.loads(pg))
	console.run()
	return console.as_dict()


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

	return jingrow.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,
	)
