import jingrow
from jingrow.boot import get_unseen_notes, get_user_pages_or_reports
from jingrow.desk.pagetype.note.note import mark_as_seen
from jingrow.tests.utils import JingrowTestCase


class TestBootData(JingrowTestCase):
	def test_get_unseen_notes(self):
		jingrow.db.delete("Note")
		jingrow.db.delete("Note Seen By")
		note = jingrow.get_pg(
			{
				"pagetype": "Note",
				"title": "Test Note",
				"notify_on_login": 1,
				"content": "Test Note 1",
				"public": 1,
			}
		)
		note.insert()

		jingrow.set_user("test@example.com")
		unseen_notes = [d.title for d in get_unseen_notes()]
		self.assertListEqual(unseen_notes, ["Test Note"])

		mark_as_seen(note.name)
		unseen_notes = [d.title for d in get_unseen_notes()]
		self.assertListEqual(unseen_notes, [])


class TestPermissionQueries(JingrowTestCase):
	@classmethod
	def setUpClass(cls) -> None:
		cls.enable_safe_exec()
		return super().setUpClass()

	def test_get_user_pages_or_reports_with_permission_query(self):
		# Create a ToDo custom report with admin user
		jingrow.set_user("Administrator")
		jingrow.get_pg(
			{
				"pagetype": "Report",
				"ref_pagetype": "ToDo",
				"report_name": "Test Admin Report",
				"report_type": "Report Builder",
				"is_standard": "No",
			}
		).insert()

		# Add permission query such that each user can only see their own custom reports
		jingrow.get_pg(
			dict(
				pagetype="Server Script",
				name="test_report_permission_query",
				script_type="Permission Query",
				reference_pagetype="Report",
				script="""conditions = f"(`tabReport`.is_standard = 'Yes' or `tabReport`.owner = '{jingrow.session.user}')"
				""",
			)
		).insert()

		# Create a ToDo custom report with test user
		jingrow.set_user("test@example.com")
		jingrow.get_pg(
			{
				"pagetype": "Report",
				"ref_pagetype": "ToDo",
				"report_name": "Test User Report",
				"report_type": "Report Builder",
				"is_standard": "No",
			}
		).insert(ignore_permissions=True)

		get_user_pages_or_reports("Report")
		allowed_reports = jingrow.cache.get_value("has_role:Report", user=jingrow.session.user)

		# Test user must not see admin user's report
		self.assertNotIn("Test Admin Report", allowed_reports)
		self.assertIn("Test User Report", allowed_reports)
