# Copyright (c) 2021, XhiveFramework Technologies and contributors
# For license information, please see license.txt

import xhiveframework
from xhiveframework import _
from xhiveframework.model.document import Document


class PrintFormatFieldTemplate(Document):
	def validate(self):
		if self.standard and not (xhiveframework.conf.developer_mode or xhiveframework.flags.in_patch):
			xhiveframework.throw(_("Enable developer mode to create a standard Print Template"))

	def before_insert(self):
		self.validate_duplicate()

	def on_update(self):
		self.validate_duplicate()
		self.export_doc()

	def validate_duplicate(self):
		if not self.standard:
			return
		if not self.field:
			return

		filters = {"document_type": self.document_type, "field": self.field}
		if not self.is_new():
			filters.update({"name": ("!=", self.name)})
		result = xhiveframework.get_all("Print Format Field Template", filters=filters, limit=1)
		if result:
			xhiveframework.throw(
				_("A template already exists for field {0} of {1}").format(
					xhiveframework.bold(self.field), xhiveframework.bold(self.document_type)
				),
				xhiveframework.DuplicateEntryError,
				title=_("Duplicate Entry"),
			)

	def export_doc(self):
		from xhiveframework.modules.utils import export_module_json

		export_module_json(self, self.standard, self.module)
