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


import jingrow

from jcloud.jcloud.pagetype.account_request.account_request import AccountRequest
from jcloud.jcloud.pagetype.jerp_consultant.jerp_consultant import JERPConsultant
from jcloud.jcloud.pagetype.site.site import Site


class JERPSite(Site):
	def __init__(self, site=None, account_request: AccountRequest = None):
		if site:
			super().__init__("Site", site)
		elif account_request:
			super().__init__(
				{
					"pagetype": "Site",
					"subdomain": account_request.subdomain,
					"domain": get_jerp_domain(),
					"bench": get_jerp_bench(),
					"apps": [{"app": app} for app in get_jerp_apps()],
					"team": "Administrator",
					"account_request": account_request.name,
					"subscription_plan": get_jerp_plan(),
					"jerp_consultant": JERPConsultant.get_one_for_country(
						account_request.country
					),
					"trial_end_date": jingrow.utils.add_days(None, 14),
				}
			)

	def rename_pooled_site(self, account_request):
		self.subdomain = account_request.subdomain
		self.is_standby = False
		self.account_request = account_request.name
		self.trial_end_date = jingrow.utils.add_days(None, 14)
		plan = get_jerp_plan()
		self._update_configuration(self.get_plan_config(plan), save=False)
		self.jerp_consultant = JERPConsultant.get_one_for_country(
			account_request.country
		)
		self.save(ignore_permissions=True)
		self.create_subscription(plan)

	def can_change_plan(self):
		return True

	def can_create_site(self):
		return True


def get_jerp_bench():
	domain = get_jerp_domain()
	cluster = get_jerp_cluster()

	proxy_servers = jingrow.get_all(
		"Proxy Server",
		[
			["status", "=", "Active"],
			["cluster", "=", cluster],
			["Proxy Server Domain", "domain", "=", domain],
		],
		pluck="name",
	)
	release_group = get_jerp_group()
	query = """
		SELECT
			bench.name
		FROM
			tabBench bench
		LEFT JOIN
			tabServer server
		ON
			bench.server = server.name
		WHERE
			server.proxy_server in %s AND bench.status = "Active" AND bench.group = %s
		ORDER BY
			server.use_for_new_sites DESC, bench.creation DESC
		LIMIT 1
	"""
	return jingrow.db.sql(query, [proxy_servers, release_group], as_dict=True)[0].name


def get_jerp_domain():
	return jingrow.db.get_single_value("Jcloud Settings", "jerp_domain")


def get_jerp_plan():
	return jingrow.db.get_single_value("Jcloud Settings", "jerp_plan")


def get_jerp_group():
	return jingrow.db.get_single_value("Jcloud Settings", "jerp_group")


def get_jerp_cluster():
	return jingrow.db.get_single_value("Jcloud Settings", "jerp_cluster")


def get_jerp_apps():
	return [app.app for app in jingrow.get_single("Jcloud Settings").jerp_apps]


def process_setup_jerp_site_job_update(job):
	if job.status == "Success":
		jingrow.db.set_value("Site", job.site, "is_jerp_setup", True)
