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

import jingrow
from jingrow.model.page import Page

from jcloud.jcloud.pagetype.telegram_message.telegram_message import TelegramMessage
from jcloud.runner import Ansible
from jcloud.utils import log_error


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

		play: DF.Link | None
		server: DF.DynamicLink
		server_type: DF.Link
		status: DF.Literal["Pending", "Running", "Success", "Failure"]
	# end: auto-generated types

	def after_insert(self):
		self.start()

	@jingrow.whitelist()
	def start(self):
		self.status = "Pending"
		self.save()
		jingrow.db.commit()
		jingrow.enqueue_pg(self.pagetype, self.name, "_start", queue="short")

	def _start(self):
		try:
			_server = jingrow.get_pg(self.server_type, self.server)
			ansible = Ansible(
				playbook="security_update.yml",
				server=_server,
				user=_server.ssh_user or "root",
				port=_server.ssh_port or 22,
				variables={"validate_pending_security_updates": True},
			)
			self.reload()
			self.play = ansible.play
			self.status = "Running"
			self.save()
			jingrow.db.commit()
			play = ansible.run()
			if play.status == "Success":
				self.succeed()
			else:
				self.fail()
		except Exception:
			log_error("Security Update Check Exception", scan=self.as_dict())
			self.fail()
		self.save()

	def succeed(self):
		self.status = "Success"

	def fail(self):
		self.status = "Failure"
		domain = jingrow.get_value("Jcloud Settings", "Jcloud Settings", "domain")
		message = f"""
Security Update Check for *{self.server}* failed.

[Security Update Check]({domain}{self.get_url()})
"""
		TelegramMessage.enqueue(message=message)
