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

from typing import List

import jingrow
from jingrow.model.page import Page

from jcloud.jcloud.pagetype.invoice.invoice import calculate_gst
from jcloud.utils import get_current_team


class SaasAppPlan(Page):
	def validate(self):
		self.validate_plan()
		self.validate_payout_percentage()

	def validate_plan(self):
		dt = jingrow.db.get_value("Site Plan", self.plan, "document_type")

		if dt != "Saas App":
			jingrow.throw("The plan must be a Saas App plan.")

	def get_total_amount(self, payment_option):
		"""
		validates if plan is gst_inclusive, checks applicable country
		:option "Monthly" or "Annual"
		"""
		team = get_current_team(True)
		amount = jingrow.db.get_value("Site Plan", self.plan, f"price_{team.currency.lower()}")
		amount = amount * 12 if payment_option == "Annual" else amount

		if team.country == "China" and self.gst_inclusive:
			amount = amount + calculate_gst(amount)

		if payment_option == "Annual" and self.annual_discount:
			amount -= (
				self.annual_discount_cny if team.country == "China" else self.annual_discount_usd
			)

		return amount

	def validate_payout_percentage(self):
		if self.is_free:
			return

		site_plan = jingrow.db.get_value("Site Plan", self.site_plan, "price_usd")
		saas_plan = jingrow.db.get_value("Site Plan", self.plan, "price_usd")
		self.payout_percentage = 100 - float("{:.2f}".format((site_plan / saas_plan) * 100))


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