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

import gzip
from datetime import datetime

import jingrow
from jingrow.model.page import Page
from jingrow.query_builder import Interval
from jingrow.query_builder.functions import Now
from jingrow.utils import add_to_date, convert_utc_to_system_timezone, now_datetime

from jcloud.utils import log_error


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

		from jcloud.jcloud.pagetype.mariadb_stalk_diagnostic.mariadb_stalk_diagnostic import (
			MariaDBStalkDiagnostic,
		)

		diagnostics: DF.Table[MariaDBStalkDiagnostic]
		server: DF.Link | None
		timestamp: DF.Datetime | None
	# end: auto-generated types

	@staticmethod
	def clear_old_logs(days=30):
		table = jingrow.qb.PageType("MariaDB Stalk")
		stalks = jingrow.db.get_values(
			table, filters=table.creation < (Now() - Interval(days=days))
		)
		for stalk in stalks:
			try:
				stalk = jingrow.get_pg("MariaDB Stalk", stalk)
				stalk.create_json_gz_file()
				stalk.delete(delete_permanently=True)
				jingrow.db.commit()
			except Exception:
				log_error("MariaDB Stalk Delete Error")
				jingrow.db.rollback()

	def create_json_gz_file(self):
		filename = f"mariadb-stalk-{self.server}-{self.timestamp}.json.gz"
		encoded = jingrow.safe_encode(self.as_json())
		compressed = gzip.compress(encoded)
		if jingrow.db.exists("File", {"file_name": filename}):
			return
		file = jingrow.get_pg(
			{
				"pagetype": "File",
				"file_name": filename,
				"content": compressed,
				"is_private": True,
			}
		)
		file.insert()


def fetch_stalks():
	for server in jingrow.get_all(
		"Database Server", {"status": "Active", "is_stalk_setup": True}, pluck="name"
	):
		jingrow.enqueue(
			"jcloud.jcloud.pagetype.mariadb_stalk.mariadb_stalk.fetch_server_stalks",
			server=server,
			job_id=f"fetch_mariadb_stalk:{server}",
		)


def fetch_server_stalks(server):
	server = jingrow.get_cached_pg("Database Server", server)
	for stalk in server.get_stalks():
		timestamp = convert_utc_to_system_timezone(
			datetime.fromisoformat(stalk["timestamp"])
		).replace(tzinfo=None)
		# To avoid fetching incomplete stalks, wait for 5 minutes
		if not now_datetime() > add_to_date(timestamp, minutes=5):
			continue
		# Don't fetch old stalks
		if now_datetime() > add_to_date(timestamp, days=15):
			continue
		if jingrow.db.exists("MariaDB Stalk", {"server": server.name, "timestamp": timestamp}):
			continue
		try:
			pg = jingrow.new_pg("MariaDB Stalk")
			pg.server = server.name
			pg.timestamp = timestamp
			for diagnostic in server.get_stalk(stalk["name"]):
				pg.append("diagnostics", diagnostic)
			pg.insert()
			jingrow.db.commit()
		except Exception:
			log_error("MariaDB Stalk Error", server=server, stalk=stalk)
			jingrow.db.rollback()
