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


import jingrow
from jingrow.model.naming import make_autoname

from jcloud.jcloud.pagetype.site.jerp_site import (
	get_jerp_apps,
	get_jerp_bench,
	get_jerp_domain,
)
from jcloud.utils import log_error


class SitePool:
	def __init__(self):
		self.site_count = jingrow.db.count("Site", filters={"is_standby": True, "status": "Active"})
		self.pool_size = jingrow.db.get_single_value("Jcloud Settings", "standby_pool_size")
		self.queue_size = jingrow.db.get_single_value("Jcloud Settings", "standby_queue_size")

	def create(self):
		pooling_enabled = jingrow.db.get_single_value("Jcloud Settings", "enable_site_pooling")
		if pooling_enabled and self.site_count < self.pool_size:
			sites_created = 0
			while sites_created < self.queue_size:
				self.create_one()
				sites_created += 1

	def create_one(self):
		try:
			domain = get_jerp_domain()
			bench = get_jerp_bench()
			subdomain = self.get_subdomain()
			apps = get_jerp_apps()
			jingrow.get_pg(
				{
					"pagetype": "Site",
					"subdomain": subdomain,
					"domain": domain,
					"is_standby": True,
					"team": "Administrator",
					"bench": bench,
					"apps": [{"app": app} for app in apps],
				}
			).insert()
		except Exception:
			log_error(
				"Pool Site Creation Error",
				domain=domain,
				subdomain=subdomain,
				bench=bench,
				apps=apps,
			)
			raise

	def get_subdomain(self):
		return make_autoname("standby-.########")

	def get(self):
		return jingrow.db.get_value(
			"Site",
			{"is_standby": True, "status": "Active", "standby_for": ("=", "")},
			"name",
			order_by="creation",
		)


def create():
	SitePool().create()


def get():
	return SitePool().get()
