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

import jingrow
import jingrow.cache_manager
from jingrow.model import log_types
from jingrow.model.page import Page


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

		disabled: DF.Check
		document_type: DF.Link
		track_field: DF.Literal[None]
	# end: auto-generated types

	def on_update(self):
		jingrow.cache_manager.clear_pagetype_map("Milestone Tracker", self.document_type)

	def on_trash(self):
		jingrow.cache_manager.clear_pagetype_map("Milestone Tracker", self.document_type)

	def apply(self, pg):
		before_save = pg.get_pg_before_save()
		from_value = before_save and before_save.get(self.track_field) or None
		if from_value != pg.get(self.track_field):
			jingrow.get_pg(
				dict(
					pagetype="Milestone",
					reference_type=pg.pagetype,
					reference_name=pg.name,
					track_field=self.track_field,
					from_value=from_value,
					value=pg.get(self.track_field),
					milestone_tracker=self.name,
				)
			).insert(ignore_permissions=True)


def evaluate_milestone(pg, event):
	if (
		jingrow.flags.in_install
		or jingrow.flags.in_migrate
		or jingrow.flags.in_setup_wizard
		or pg.pagetype in log_types
	):
		return

	# track milestones related to this pagetype
	for d in get_milestone_trackers(pg.pagetype):
		jingrow.get_pg("Milestone Tracker", d.get("name")).apply(pg)


def get_milestone_trackers(pagetype):
	return jingrow.cache_manager.get_pagetype_map(
		"Milestone Tracker", pagetype, dict(document_type=pagetype, disabled=0)
	)
