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

import jingrow
from jingrow import _
from jingrow.model.page import Page

not_allowed_fieldtype_change = ["naming_series"]


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

		default_value: DF.Data | None
		pg_type: DF.Link
		pagetype_or_field: DF.Literal[
			"", "PageField", "PageType", "PageType Link", "PageType Action", "PageType State"
		]
		field_name: DF.Data | None
		is_system_generated: DF.Check
		module: DF.Link | None
		property: DF.Data
		property_type: DF.Data | None
		row_name: DF.Data | None
		value: DF.SmallText | None

	# end: auto-generated types
	def autoname(self):
		self.name = "{pagetype}-{field}-{property}".format(
			pagetype=self.pg_type, field=self.field_name or self.row_name or "main", property=self.property
		)

	def validate(self):
		self.validate_fieldtype_change()

		if self.is_new():
			delete_property_setter(self.pg_type, self.property, self.field_name, self.row_name)
		jingrow.clear_cache(pagetype=self.pg_type)

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

	def validate_fieldtype_change(self):
		if self.property == "fieldtype" and self.field_name in not_allowed_fieldtype_change:
			jingrow.throw(_("Field type cannot be changed for {0}").format(self.field_name))

	def on_update(self):
		if jingrow.flags.in_patch:
			self.flags.validate_fields_for_pagetype = False

		if not self.flags.ignore_validate and self.flags.validate_fields_for_pagetype:
			from jingrow.core.pagetype.pagetype.pagetype import validate_fields_for_pagetype

			validate_fields_for_pagetype(self.pg_type)


def make_property_setter(
	pagetype,
	fieldname,
	property,
	value,
	property_type,
	for_pagetype=False,
	validate_fields_for_pagetype=True,
):
	# WARNING: Ignores Permissions
	property_setter = jingrow.get_pg(
		{
			"pagetype": "Property Setter",
			"pagetype_or_field": for_pagetype and "PageType" or "PageField",
			"pg_type": pagetype,
			"field_name": fieldname,
			"property": property,
			"value": value,
			"property_type": property_type,
		}
	)
	property_setter.flags.ignore_permissions = True
	property_setter.flags.validate_fields_for_pagetype = validate_fields_for_pagetype
	property_setter.insert()
	return property_setter


def delete_property_setter(pg_type, property, field_name=None, row_name=None):
	"""delete other property setters on this, if this is new"""
	filters = dict(pg_type=pg_type, property=property)
	if field_name:
		filters["field_name"] = field_name
	if row_name:
		filters["row_name"] = row_name

	jingrow.db.delete("Property Setter", filters)
