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


import jingrow
from jingrow.utils import update_progress_bar


def execute():
	jingrow.db.sql("DROP TABLE IF EXISTS `tabSubscription`")

	jingrow.reload_pg("jcloud", "pagetype", "subscription", force=True)
	jingrow.reload_pg("jcloud", "pagetype", "site")

	active_sites = jingrow.db.get_all(
		"Site",
		filters={"status": "Active", "free": False, "team": ("is", "set")},
		fields=["name", "team", "plan"],
	)
	for i, site in enumerate(active_sites):
		update_progress_bar("Creating Subscriptions", i, len(active_sites))

		# skip if already exists
		if jingrow.db.exists(
			"Subscription",
			{"team": site.team, "document_type": "Site", "document_name": site.name},
		):
			continue

		try:
			jingrow.get_pg(
				pagetype="Subscription",
				enabled=1,
				team=site.team,
				document_type="Site",
				document_name=site.name,
				plan=site.plan,
				interval="Daily",
			).insert()
		except jingrow.DuplicateEntryError:
			print(f"Failed to create subscription for site {site}")

	print()
