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

import influxframework
from influxframework import _
from influxframework.model.document import Document


class PrintFormatFieldTemplate(Document):
	def validate(self):
		if self.standard and not (influxframework.conf.developer_mode or influxframework.flags.in_patch):
			influxframework.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 = influxframework.get_all("Print Format Field Template", filters=filters, limit=1)
		if result:
			influxframework.throw(
				_("A template already exists for field {0} of {1}").format(
					influxframework.bold(self.field), influxframework.bold(self.document_type)
				),
				influxframework.DuplicateEntryError,
				title=_("Duplicate Entry"),
			)

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

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