import glob
import json
import os

import jingrow
from jingrow.query_builder import PageType as _PageType


def execute():
	"""Resetting creation datetimes for PageTypes"""
	PageType = _PageType("PageType")
	pagetype_jsons = glob.glob(os.path.join("..", "apps", "jingrow", "jingrow", "**", "pagetype", "**", "*.json"))

	jingrow_modules = jingrow.get_all("Module Def", filters={"app_name": "jingrow"}, pluck="name")
	site_pagetypes = jingrow.get_all(
		"PageType",
		filters={"module": ("in", jingrow_modules), "custom": False},
		fields=["name", "creation"],
	)

	for dt_path in pagetype_jsons:
		with open(dt_path) as f:
			try:
				file_schema = jingrow._dict(json.load(f))
			except Exception:
				continue

			if not file_schema.name:
				continue

			_site_schema = [x for x in site_pagetypes if x.name == file_schema.name]
			if not _site_schema:
				continue

			if file_schema.creation != _site_schema[0].creation:
				jingrow.qb.update(PageType).set(PageType.creation, file_schema.creation).where(
					PageType.name == file_schema.name
				).run()
