# Copyright (c) 2024, JINGROW
# For license information, please see license.txt

import json
from typing import TYPE_CHECKING

import jingrow
from jingrow.model.page import Page

if TYPE_CHECKING:
	from jcloud.jcloud.pagetype.bench.bench import Bench


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

		bench: DF.Link | None
		command: DF.Code | None
		directory: DF.Data | None
		duration: DF.Float
		output: DF.Code | None
		returncode: DF.Int
		save_output: DF.Check
		subdir: DF.Data | None
		traceback: DF.Code | None
	# end: auto-generated types

	def run_command(self):
		jingrow.only_for("System Manager")

		bench: "Bench" = jingrow.get_pg("Bench", self.bench)
		try:
			result = bench.docker_execute(
				self.command,
				self.subdir,
				self.save_output,
			)
		except Exception:
			self.save_output = False
			self.output = None
			self.traceback = jingrow.get_traceback()
			return

		self.output = result.get("output")
		self.directory = result.get("directory")
		self.traceback = result.get("traceback")
		self.returncode = result.get("returncode")
		self.duration = result.get("duration")
		jingrow.db.commit()


@jingrow.whitelist()
def run_command(pg):
	bench_shell: "BenchShell" = jingrow.get_pg(json.loads(pg))
	bench_shell.run_command()
	return bench_shell.as_dict()
