# Copyright (c) 2019, InfluxFramework LLC
# License: MIT. See LICENSE
import influxframework
from influxframework.core.doctype.user.user import get_system_users
from influxframework.desk.form.assign_to import add as assign_task
from influxframework.tests.utils import InfluxFrameworkTestCase


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

		assign_task(
			{"assign_to": [user], "doctype": "ToDo", "name": todo.name, "description": todo.description}
		)
		log_type = influxframework.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()

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

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


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


def get_todo():
	if not influxframework.get_all("ToDo"):
		return influxframework.get_doc({"doctype": "ToDo", "description": "Test for Notification"}).insert()

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


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