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

import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.model.naming import parse_naming_series
from jingrow.utils.data import evaluate_filters


class PageNamingRule(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.core.pagetype.page_naming_rule_condition.page_naming_rule_condition import DocumentNamingRuleCondition
		from jingrow.types import DF

		conditions: DF.Table[DocumentNamingRuleCondition]
		counter: DF.Int
		disabled: DF.Check
		document_type: DF.Link
		prefix: DF.Data
		prefix_digits: DF.Int
		priority: DF.Int
	# end: auto-generated types
	def validate(self):
		self.validate_fields_in_conditions()

	def clear_pagetype_map(self):
		jingrow.cache_manager.clear_pagetype_map(self.pagetype, self.document_type)

	def on_update(self):
		self.clear_pagetype_map()

	def on_trash(self):
		self.clear_pagetype_map()

	def validate_fields_in_conditions(self):
		if self.has_value_changed("document_type"):
			pagefields = [x.fieldname for x in jingrow.get_meta(self.document_type).fields]
			for condition in self.conditions:
				if condition.field not in pagefields:
					jingrow.throw(
						_("{0} is not a field of pagetype {1}").format(
							jingrow.bold(condition.field), jingrow.bold(self.document_type)
						)
					)

	def apply(self, pg):
		"""
		Apply naming rules for the given document. Will set `name` if the rule is matched.
		"""
		if self.conditions:
			if not evaluate_filters(
				pg, [(self.document_type, d.field, d.condition, d.value) for d in self.conditions]
			):
				return

		counter = jingrow.db.get_value(self.pagetype, self.name, "counter", for_update=True) or 0
		naming_series = parse_naming_series(self.prefix, pg=pg)

		pg.name = naming_series + ("%0" + str(self.prefix_digits) + "d") % (counter + 1)
		jingrow.db.set_value(self.pagetype, self.name, "counter", counter + 1)
