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


import jingrow
from tqdm import tqdm


def execute():
	Server = jingrow.qb.PageType("Server")
	DatabaseServer = jingrow.qb.PageType("Database Server")
	VirtualMachine = jingrow.qb.PageType("Virtual Machine")
	ServerPlan = jingrow.qb.PageType("Server Plan")

	servers = (
		jingrow.qb.from_(Server)
		.select(Server.name, Server.team, ServerPlan.disk, VirtualMachine.disk_size)
		.join(VirtualMachine)
		.on(Server.virtual_machine == VirtualMachine.name)
		.join(ServerPlan)
		.on(Server.plan == ServerPlan.name)
		.where(ServerPlan.disk < VirtualMachine.disk_size)
		.where(Server.public == 0)
		.run(as_dict=True)
	)

	database_servers = (
		jingrow.qb.from_(DatabaseServer)
		.select(
			DatabaseServer.name, DatabaseServer.team, ServerPlan.disk, VirtualMachine.disk_size
		)
		.join(VirtualMachine)
		.on(DatabaseServer.virtual_machine == VirtualMachine.name)
		.join(ServerPlan)
		.on(DatabaseServer.plan == ServerPlan.name)
		.where(ServerPlan.disk < VirtualMachine.disk_size)
		.where(DatabaseServer.public == 0)
		.run(as_dict=True)
	)

	for server in tqdm(servers):
		jingrow.get_pg("Server", server.name).create_subscription_for_storage()

	for database_server in tqdm(database_servers):
		jingrow.get_pg(
			"Database Server", database_server.name
		).create_subscription_for_storage()
