# Copyright (c) 2021, JINGROW
# For license information, please see license.txt
from __future__ import annotations

import json

import jingrow

from jcloud.jcloud.pagetype.server.server import BaseServer
from jcloud.runner import Ansible
from jcloud.utils import log_error


class MonitorServer(BaseServer):
	# 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

		agent_password: DF.Password | None
		cluster: DF.Link | None
		default_server: DF.Data | None
		domain: DF.Link | None
		jingrow_public_key: DF.Code | None
		jingrow_user_password: DF.Password | None
		grafana_password: DF.Password | None
		grafana_username: DF.Data | None
		hostname: DF.Data
		ip: DF.Data | None
		is_server_setup: DF.Check
		monitoring_password: DF.Password | None
		node_exporter_dashboard_path: DF.Data | None
		private_ip: DF.Data
		private_mac_address: DF.Data | None
		private_vlan_id: DF.Data | None
		prometheus_data_directory: DF.Data | None
		provider: DF.Literal["Generic", "Scaleway", "AWS EC2", "OCI"]
		root_public_key: DF.Code | None
		status: DF.Literal["Pending", "Installing", "Active", "Broken", "Archived"]
		virtual_machine: DF.Link | None
	# end: auto-generated types

	def validate(self):
		self.validate_agent_password()
		self.validate_grafana_password()
		self.validate_monitoring_password()

	def validate_monitoring_password(self):
		if not self.monitoring_password:
			self.monitoring_password = jingrow.generate_hash()

	def validate_grafana_password(self):
		if not self.grafana_password:
			self.grafana_password = jingrow.generate_hash(length=32)

	def _setup_server(self):
		agent_password = self.get_password("agent_password")
		agent_repository_url = self.get_agent_repository_url()
		monitoring_password = self.get_password("monitoring_password")
		certificate_name = jingrow.db.get_value(
			"TLS Certificate", {"wildcard": True, "domain": self.domain}, "name"
		)
		certificate = jingrow.get_pg("TLS Certificate", certificate_name)

		registries = []
		for registry in jingrow.get_all("Registry Server"):
			registry = jingrow.get_pg("Registry Server", registry.name)
			registries.append(
				{
					"name": registry.name,
					"monitoring_password": registry.get_password("monitoring_password"),
				}
			)

		log_servers = []
		for log in jingrow.get_all("Log Server"):
			log = jingrow.get_pg("Log Server", log.name)
			log_servers.append(
				{
					"name": log.name,
					"monitoring_password": log.get_password("monitoring_password"),
				}
			)

		clusters = []
		for cluster in jingrow.get_all("Cluster"):
			cluster = jingrow.get_pg("Cluster", cluster.name)
			clusters.append(
				{
					"name": cluster.name,
					"monitoring_password": cluster.get_password("monitoring_password"),
				}
			)
		jcloud_url = jingrow.utils.get_url()
		settings = jingrow.get_single("Jcloud Settings")
		monitor_token = settings.monitor_token
		jcloud_monitoring_password = settings.get_password("jcloud_monitoring_password")
		try:
			ansible = Ansible(
				playbook="monitor.yml",
				server=self,
				variables={
					"server": self.name,
					"workers": 1,
					"domain": self.domain,
					"agent_password": agent_password,
					"agent_repository_url": agent_repository_url,
					"monitor": True,
					"monitoring_password": monitoring_password,
					"jcloud_monitoring_password": jcloud_monitoring_password,
					"jcloud_app_server": jingrow.local.site,
					"jcloud_db_server": f"db.{jingrow.local.site}",
					"jcloud_db_replica_server": f"db2.{jingrow.local.site}" if jingrow.conf.replica_host else "",
					"jcloud_url": jcloud_url,
					"prometheus_data_directory": self.prometheus_data_directory,
					"monitor_token": monitor_token,
					"registries_json": json.dumps(registries),
					"log_servers_json": json.dumps(log_servers),
					"clusters_json": json.dumps(clusters),
					"private_ip": self.private_ip,
					"grafana_password": self.get_password("grafana_password"),
					"certificate_private_key": certificate.private_key,
					"certificate_full_chain": certificate.full_chain,
					"certificate_intermediate_chain": certificate.intermediate_chain,
				},
			)
			play = ansible.run()
			self.reload()
			if play.status == "Success":
				self.status = "Active"
				self.is_server_setup = True
			else:
				self.status = "Broken"
		except Exception:
			self.status = "Broken"
			log_error("Monitor Server Setup Exception", server=self.as_dict())
		self.save()

	@jingrow.whitelist()
	def reconfigure_monitor_server(self):
		jingrow.enqueue_pg(self.pagetype, self.name, "_reconfigure_monitor_server", queue="long", timeout=1200)

	def _reconfigure_monitor_server(self):
		settings = jingrow.get_single("Jcloud Settings")
		jcloud_monitoring_password = settings.get_password("jcloud_monitoring_password")
		monitoring_password = self.get_password("monitoring_password")

		registries = []
		for registry in jingrow.get_all("Registry Server"):
			registry = jingrow.get_pg("Registry Server", registry.name)
			registries.append(
				{
					"name": registry.name,
					"monitoring_password": registry.get_password("monitoring_password"),
				}
			)

		log_servers = []
		for log in jingrow.get_all("Log Server"):
			log = jingrow.get_pg("Log Server", log.name)
			log_servers.append(
				{
					"name": log.name,
					"monitoring_password": log.get_password("monitoring_password"),
				}
			)

		clusters = []
		for cluster in jingrow.get_all("Cluster"):
			cluster = jingrow.get_pg("Cluster", cluster.name)
			clusters.append(
				{
					"name": cluster.name,
					"monitoring_password": cluster.get_password("monitoring_password"),
				}
			)

		try:
			ansible = Ansible(
				playbook="reconfigure_monitoring.yml",
				server=self,
				variables={
					"server": self.name,
					"monitoring_password": monitoring_password,
					"jcloud_monitoring_password": jcloud_monitoring_password,
					"jcloud_app_server": jingrow.local.site,
					"jcloud_db_server": f"db.{jingrow.local.site}",
					"jcloud_db_replica_server": f"db2.{jingrow.local.site}" if jingrow.conf.replica_host else "",
					"registries_json": json.dumps(registries),
					"log_servers_json": json.dumps(log_servers),
					"clusters_json": json.dumps(clusters),
					"grafana_password": self.get_password("grafana_password"),
				},
			)
			ansible.run()
		except Exception:
			log_error("Monitoring Server Setup Exception", server=self.as_dict())

	@jingrow.whitelist()
	def show_grafana_password(self):
		return self.get_password("grafana_password")
