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

from typing import List

import jingrow
from jingrow import cint

from jcloud.jcloud.pagetype.site_plan.plan import Plan


class MarketplaceAppPlan(Plan):
	# 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 jcloud.jcloud.pagetype.plan_feature.plan_feature import PlanFeature
		from jcloud.marketplace.pagetype.app_plan_version.app_plan_version import AppPlanVersion
		from jingrow.core.pagetype.has_role.has_role import HasRole
		from jingrow.types import DF

		app: DF.Link
		available_on_versions: DF.Table[AppPlanVersion]
		enabled: DF.Check
		features: DF.Table[PlanFeature]
		interval: DF.Literal["Daily", "Monthly", "Yearly"]
		price_cny: DF.Currency
		price_usd: DF.Currency
		roles: DF.Table[HasRole]
		title: DF.Data | None
	# end: auto-generated types
	dashboard_fields = ["app", "name", "title", "price_cny", "price_usd", "enabled"]

	@staticmethod
	def get_list_query(query):
		plans = query.run(as_dict=True)
		for plan in plans:
			plan["features"] = get_app_plan_features(plan.name)

		return plans

	def after_insert(self):
		self.update_marketplace_app_subscription_type()

	def on_update(self):
		self.update_marketplace_app_subscription_type()

	def update_marketplace_app_subscription_type(self):
		if cint(self.price_cny) > 0 or cint(self.price_usd) > 0:
			jingrow.db.set_value(
				"Marketplace App",
				self.app,
				"subscription_type",
				"Paid",
			)

	@staticmethod
	def create_marketplace_app_subscription(
		site_name, app_name, plan_name, team_name, while_site_creation=False
	):
		marketplace_app = jingrow.db.get_value("Marketplace App", {"app": app_name})
		subscription = jingrow.db.exists(
			"Subscription",
			{
				"site": site_name,
				"document_type": "Marketplace App",
				"document_name": marketplace_app,
			},
		)

		# If already exists, update the plan and activate
		if subscription:
			subscription = jingrow.get_pg(
				"Subscription",
				subscription,
				for_update=True,
			)

			subscription.plan = plan_name
			subscription.enabled = 1
			subscription.save(ignore_permissions=True)
			subscription.reload()

			return subscription

		return jingrow.get_pg(
			{
				"pagetype": "Subscription",
				"document_type": "Marketplace App",
				"document_name": app_name,
				"plan_type": "Marketplace App Plan",
				"plan": plan_name,
				"site": site_name,
				"team": team_name,
			}
		).insert(ignore_permissions=True)


def get_app_plan_features(app_plan: str) -> List[str]:
	features = jingrow.get_all(
		"Plan Feature", filters={"parent": app_plan}, pluck="description", order_by="idx"
	)

	return features
