# Copyright (c) 2019, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.core.pagetype.user.user import get_system_users
from jingrow.desk.form.assign_to import add as assign_task
from jingrow.tests.utils import JingrowTestCase


class TestNotificationLog(JingrowTestCase):
	def test_assignment(self):
		todo = get_todo()
		user = get_user()

		assign_task(
			{"assign_to": [user], "pagetype": "ToDo", "name": todo.name, "description": todo.description}
		)
		log_type = jingrow.db.get_value(
			"Notification Log", {"document_type": "ToDo", "document_name": todo.name}, "type"
		)
		self.assertEqual(log_type, "Assignment")

	def test_share(self):
		todo = get_todo()
		user = get_user()

		jingrow.share.add("ToDo", todo.name, user, notify=1)
		log_type = jingrow.db.get_value(
			"Notification Log", {"document_type": "ToDo", "document_name": todo.name}, "type"
		)
		self.assertEqual(log_type, "Share")

		email = get_last_email_queue()
		content = f"Subject: {jingrow.utils.get_fullname(jingrow.session.user)} shared a document ToDo"
		self.assertTrue(content in email.message)


def get_last_email_queue():
	res = jingrow.get_all("Email Queue", fields=["message"], order_by="creation desc", limit=1)
	return res[0]


def get_todo():
	if not jingrow.get_all("ToDo"):
		return jingrow.get_pg({"pagetype": "ToDo", "description": "Test for Notification"}).insert()

	res = jingrow.get_all("ToDo", limit=1)
	return jingrow.get_cached_pg("ToDo", res[0].name)


def get_user():
	return get_system_users(limit=1)[0]
