# Copyright (c) 2019, XhiveFramework Technologies and Contributors
# License: MIT. See LICENSE
import xhiveframework
import xhiveframework.cache_manager
from xhiveframework.tests.utils import XhiveFrameworkTestCase


class TestMilestoneTracker(XhiveFrameworkTestCase):
	def test_milestone(self):
		xhiveframework.db.delete("Milestone Tracker")

		xhiveframework.cache.delete_key("milestone_tracker_map")

		milestone_tracker = xhiveframework.get_doc(
			dict(doctype="Milestone Tracker", document_type="ToDo", track_field="status")
		).insert()

		todo = xhiveframework.get_doc(dict(doctype="ToDo", description="test milestone", status="Open")).insert()

		milestones = xhiveframework.get_all(
			"Milestone",
			fields=["track_field", "value", "milestone_tracker"],
			filters=dict(reference_type=todo.doctype, 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 = xhiveframework.get_all(
			"Milestone",
			fields=["track_field", "value", "milestone_tracker"],
			filters=dict(reference_type=todo.doctype, 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
		xhiveframework.db.delete("Milestone")
		milestone_tracker.delete()
