# Copyright (c) 2019, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
import jingrow.cache_manager
from jingrow.tests.utils import JingrowTestCase


class TestMilestoneTracker(JingrowTestCase):
	def test_milestone(self):
		jingrow.db.delete("Milestone Tracker")

		jingrow.cache.delete_key("milestone_tracker_map")

		milestone_tracker = jingrow.get_pg(
			dict(pagetype="Milestone Tracker", document_type="ToDo", track_field="status")
		).insert()

		todo = jingrow.get_pg(dict(pagetype="ToDo", description="test milestone", status="Open")).insert()

		milestones = jingrow.get_all(
			"Milestone",
			fields=["track_field", "value", "milestone_tracker"],
			filters=dict(reference_type=todo.pagetype, reference_name=todo.name),
		)

		self.assertEqual(len(milestones), 1)
		self.assertEqual(milestones[0].track_field, "status")
		self.assertEqual(milestones[0].value, "Open")

		todo.status = "Closed"
		todo.save()

		milestones = jingrow.get_all(
			"Milestone",
			fields=["track_field", "value", "milestone_tracker"],
			filters=dict(reference_type=todo.pagetype, reference_name=todo.name),
			order_by="modified desc",
		)

		self.assertEqual(len(milestones), 2)
		self.assertEqual(milestones[0].track_field, "status")
		self.assertEqual(milestones[0].value, "Closed")

		# cleanup
		jingrow.db.delete("Milestone")
		milestone_tracker.delete()
