# Copyright (c) 2015, XhiveFramework Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import xhiveframework
from xhiveframework.cache_manager import clear_controller_cache
from xhiveframework.desk.doctype.todo.todo import ToDo
from xhiveframework.tests.test_api import XhiveFrameworkAPITestCase
from xhiveframework.tests.utils import XhiveFrameworkTestCase, patch_hooks


class TestHooks(XhiveFrameworkTestCase):
	def test_hooks(self):
		hooks = xhiveframework.get_hooks()
		self.assertTrue(isinstance(hooks.get("app_name"), list))
		self.assertTrue(isinstance(hooks.get("doc_events"), dict))
		self.assertTrue(isinstance(hooks.get("doc_events").get("*"), dict))
		self.assertTrue(isinstance(hooks.get("doc_events").get("*"), dict))
		self.assertTrue(
			"xhiveframework.desk.notifications.clear_doctype_notifications"
			in hooks.get("doc_events").get("*").get("on_update")
		)

	def test_override_doctype_class(self):
		from xhiveframework import hooks

		# Set hook
		hooks.override_doctype_class = {"ToDo": ["xhiveframework.tests.test_hooks.CustomToDo"]}

		# Clear cache
		xhiveframework.cache.delete_value("app_hooks")
		clear_controller_cache("ToDo")

		todo = xhiveframework.get_doc(doctype="ToDo", description="asdf")
		self.assertTrue(isinstance(todo, CustomToDo))

	def test_has_permission(self):
		from xhiveframework import hooks

		# Set hook
		address_has_permission_hook = hooks.has_permission.get("Address", [])
		if isinstance(address_has_permission_hook, str):
			address_has_permission_hook = [address_has_permission_hook]

		address_has_permission_hook.append("xhiveframework.tests.test_hooks.custom_has_permission")

		hooks.has_permission["Address"] = address_has_permission_hook

		# Clear cache
		xhiveframework.cache.delete_value("app_hooks")

		# Init User and Address
		username = "test@example.com"
		user = xhiveframework.get_doc("User", username)
		user.add_roles("System Manager")
		address = xhiveframework.new_doc("Address")

		# Test!
		self.assertTrue(xhiveframework.has_permission("Address", doc=address, user=username))

		address.flags.dont_touch_me = True
		self.assertFalse(xhiveframework.has_permission("Address", doc=address, user=username))

	def test_ignore_links_on_delete(self):
		email_unsubscribe = xhiveframework.get_doc(
			{"doctype": "Email Unsubscribe", "email": "test@example.com", "global_unsubscribe": 1}
		).insert()

		event = xhiveframework.get_doc(
			{
				"doctype": "Event",
				"subject": "Test Event",
				"starts_on": "2022-12-21",
				"event_type": "Public",
				"event_participants": [
					{
						"reference_doctype": "Email Unsubscribe",
						"reference_docname": email_unsubscribe.name,
					}
				],
			}
		).insert()
		self.assertRaises(xhiveframework.LinkExistsError, email_unsubscribe.delete)

		event.event_participants = []
		event.save()

		todo = xhiveframework.get_doc(
			{
				"doctype": "ToDo",
				"description": "Test ToDo",
				"reference_type": "Event",
				"reference_name": event.name,
			}
		)
		todo.insert()

		event.delete()


class TestAPIHooks(XhiveFrameworkAPITestCase):
	def test_auth_hook(self):
		with patch_hooks({"auth_hooks": ["xhiveframework.tests.test_hooks.custom_auth"]}):
			site_url = xhiveframework.utils.get_site_url(xhiveframework.local.site)
			response = self.get(
				site_url + "/api/method/xhiveframework.auth.get_logged_user",
				headers={"Authorization": "Bearer set_test_example_user"},
			)
			# Test!
			self.assertTrue(response.json.get("message") == "test@example.com")


def custom_has_permission(doc, ptype, user):
	if doc.flags.dont_touch_me:
		return False


def custom_auth():
	auth_type, token = xhiveframework.get_request_header("Authorization", "Bearer ").split(" ")
	if token == "set_test_example_user":
		xhiveframework.set_user("test@example.com")


class CustomToDo(ToDo):
	pass
