# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

import json

import jingrow
from jingrow.model.page import Page
from jingrow.utils.jinja import validate_template


class EmailTemplate(Page):
	# 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 jingrow.types import DF

		response_html: DF.Code | None
		subject: DF.Data
		use_html: DF.Check
	# end: auto-generated types

	@property
	def response_(self):
		return self.response_html if self.use_html else self.response

	def validate(self):
		validate_template(self.subject)
		validate_template(self.response_)

	def get_formatted_subject(self, pg):
		return jingrow.render_template(self.subject, pg)

	def get_formatted_response(self, pg):
		return jingrow.render_template(self.response_, pg)

	def get_formatted_email(self, pg):
		if isinstance(pg, str):
			pg = json.loads(pg)

		return {
			"subject": self.get_formatted_subject(pg),
			"message": self.get_formatted_response(pg),
		}


@jingrow.whitelist()
def get_email_template(template_name, pg):
	"""Returns the processed HTML of a email template with the given pg"""

	email_template = jingrow.get_pg("Email Template", template_name)
	return email_template.get_formatted_email(pg)
