# Copyright (c) 2017, JINGROW
# License: MIT. See LICENSE

import json

import jingrow
import jingrow.utils
from jingrow import _
from jingrow.model.page import Page
from jingrow.utils.jinja import validate_template
from jingrow.utils.weasyprint import download_pdf, get_html


class PrintFormat(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

		absolute_value: DF.Check
		align_labels_right: DF.Check
		css: DF.Code | None
		custom_format: DF.Check
		default_print_language: DF.Link | None
		disabled: DF.Check
		pg_type: DF.Link
		font: DF.Data | None
		font_size: DF.Int
		format_data: DF.Code | None
		html: DF.Code | None
		line_breaks: DF.Check
		margin_bottom: DF.Float
		margin_left: DF.Float
		margin_right: DF.Float
		margin_top: DF.Float
		module: DF.Link | None
		page_number: DF.Literal[
			"Hide", "Top Left", "Top Center", "Top Right", "Bottom Left", "Bottom Center", "Bottom Right"
		]
		pdf_generator: DF.Literal["wkhtmltopdf"]
		print_format_builder: DF.Check
		print_format_builder_beta: DF.Check
		print_format_type: DF.Literal["Jinja", "JS"]
		raw_commands: DF.Code | None
		raw_printing: DF.Check
		show_section_headings: DF.Check
		standard: DF.Literal["No", "Yes"]

	# end: auto-generated types

	def onload(self):
		templates = jingrow.get_all(
			"Print Format Field Template",
			fields=["template", "field", "name"],
			filters={"document_type": self.pg_type},
		)
		self.set_onload("print_templates", templates)

	def get_html(self, pagename, letterhead=None):
		return get_html(self.pg_type, pagename, self.name, letterhead)

	def download_pdf(self, pagename, letterhead=None):
		return download_pdf(self.pg_type, pagename, self.name, letterhead)

	def validate(self):
		if (
			self.standard == "Yes"
			and not jingrow.local.conf.get("developer_mode")
			and not jingrow.flags.in_migrate
			and not jingrow.flags.in_install
			and not jingrow.flags.in_test
		):
			jingrow.throw(jingrow._("Standard Print Format cannot be updated"))

		# old_pg_type is required for clearing item cache
		self.old_pg_type = jingrow.db.get_value("Print Format", self.name, "pg_type")

		self.extract_images()

		if not self.module:
			self.module = jingrow.db.get_value("PageType", self.pg_type, "module")

		if self.html and self.print_format_type != "JS":
			validate_template(self.html)

		if self.custom_format and self.raw_printing and not self.raw_commands:
			jingrow.throw(_("{0} are required").format(jingrow.bold(_("Raw Commands"))), jingrow.MandatoryError)

		if self.custom_format and not self.html and not self.raw_printing:
			jingrow.throw(_("{0} is required").format(jingrow.bold(_("HTML"))), jingrow.MandatoryError)

	def extract_images(self):
		from jingrow.core.pagetype.file.utils import extract_images_from_html

		if self.print_format_builder_beta:
			return

		if self.format_data:
			data = json.loads(self.format_data)
			for df in data:
				if df.get("fieldtype") and df["fieldtype"] in ("HTML", "Custom HTML") and df.get("options"):
					df["options"] = extract_images_from_html(self, df["options"])
			self.format_data = json.dumps(data)

	def on_update(self):
		if hasattr(self, "old_pg_type") and self.old_pg_type:
			jingrow.clear_cache(pagetype=self.old_pg_type)
		if self.pg_type:
			jingrow.clear_cache(pagetype=self.pg_type)

		self.export_pg()

	def after_rename(self, old: str, new: str, *args, **kwargs):
		if self.pg_type:
			jingrow.clear_cache(pagetype=self.pg_type)

		# update property setter default_print_format if set
		jingrow.db.set_value(
			"Property Setter",
			{
				"pagetype_or_field": "PageType",
				"pg_type": self.pg_type,
				"property": "default_print_format",
				"value": old,
			},
			"value",
			new,
		)

	def export_pg(self):
		from jingrow.modules.utils import export_module_json

		return export_module_json(self, self.standard == "Yes", self.module)

	def on_trash(self):
		if self.pg_type:
			jingrow.clear_cache(pagetype=self.pg_type)


@jingrow.whitelist()
def make_default(name):
	"""Set print format as default"""
	jingrow.has_permission("Print Format", "write")

	print_format = jingrow.get_pg("Print Format", name)

	pagetype = jingrow.get_pg("PageType", print_format.pg_type)
	if pagetype.custom:
		pagetype.default_print_format = name
		pagetype.save()
	else:
		# "Customize form"
		jingrow.make_property_setter(
			{
				"pagetype_or_field": "PageType",
				"pagetype": print_format.pg_type,
				"property": "default_print_format",
				"value": name,
			}
		)

	jingrow.msgprint(
		jingrow._("{0} is now default print format for {1} pagetype").format(
			jingrow.bold(name), jingrow.bold(print_format.pg_type)
		)
	)
