import jingrow
from jingrow.utils import cint

# This patch aims to apply & delete all the customization
# on custom pagetypes done through customize form

# This is required because customize form in now blocked
# for custom pagetypes and user may not be able to
# see previous customization


def execute():
	custom_pagetypes = jingrow.get_all("PageType", filters={"custom": 1})

	for pagetype in custom_pagetypes:
		property_setters = jingrow.get_all(
			"Property Setter",
			filters={"pg_type": pagetype.name, "pagetype_or_field": "PageField"},
			fields=["name", "property", "value", "property_type", "field_name"],
		)

		custom_fields = jingrow.get_all("Custom Field", filters={"dt": pagetype.name}, fields=["*"])

		property_setter_map = {}

		for prop in property_setters:
			property_setter_map[prop.field_name] = prop
			jingrow.db.delete("Property Setter", {"name": prop.name})

		meta = jingrow.get_meta(pagetype.name)

		for df in meta.fields:
			ps = property_setter_map.get(df.fieldname, None)
			if ps:
				value = cint(ps.value) if ps.property_type == "Int" else ps.value
				df.set(ps.property, value)

		for cf in custom_fields:
			cf.pop("parenttype")
			cf.pop("parentfield")
			cf.pop("parent")
			cf.pop("name")
			field = meta.get_field(cf.fieldname)
			if field:
				field.update(cf)
			else:
				df = jingrow.new_pg("PageField", parent_pg=meta, parentfield="fields")
				df.update(cf)
				meta.fields.append(df)
			jingrow.db.delete("Custom Field", {"name": cf.name})

		meta.save()
