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

import json

import jingrow
from jingrow.model.page import Page

from jcloud.agent import Agent


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

		build_server: DF.Link
		cache_target: DF.Data
		command: DF.Code
		cwd: DF.Data | None
		image_tag: DF.Data | None
		output: DF.Code | None
		returncode: DF.Int
	# end: auto-generated types

	def run_command(self):
		jingrow.only_for("System Manager")
		result = self._run_command() or {}
		self.output = result.get("output", "# no-output")
		self.cwd = result.get("cwd")
		self.image_tag = result.get("image_tag")
		self.returncode = result.get("returncode")
		jingrow.db.commit()

	def _run_command(self):
		if not self.build_server:
			jingrow.throw("Please select a <b>Build Server</b>.")

		return Agent(self.build_server).run_command_in_docker_cache(
			self.command,
			self.cache_target,
		)


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