# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.cache_manager import clear_controller_cache
from jingrow.desk.pagetype.todo.todo import ToDo
from jingrow.tests.test_api import JingrowAPITestCase
from jingrow.tests.utils import JingrowTestCase, patch_hooks


class TestHooks(JingrowTestCase):
	def test_hooks(self):
		hooks = jingrow.get_hooks()
		self.assertTrue(isinstance(hooks.get("app_name"), list))
		self.assertTrue(isinstance(hooks.get("pg_events"), dict))
		self.assertTrue(isinstance(hooks.get("pg_events").get("*"), dict))
		self.assertTrue(isinstance(hooks.get("pg_events").get("*"), dict))
		self.assertTrue(
			"jingrow.desk.notifications.clear_pagetype_notifications"
			in hooks.get("pg_events").get("*").get("on_update")
		)

	def test_override_pagetype_class(self):
		from jingrow import hooks

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

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

		todo = jingrow.get_pg(pagetype="ToDo", description="asdf")
		self.assertTrue(isinstance(todo, CustomToDo))

	def test_has_permission(self):
		from jingrow 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("jingrow.tests.test_hooks.custom_has_permission")

		hooks.has_permission["Address"] = address_has_permission_hook

		wildcard_has_permission_hook = hooks.has_permission.get("*", [])
		if isinstance(wildcard_has_permission_hook, str):
			wildcard_has_permission_hook = [wildcard_has_permission_hook]

		wildcard_has_permission_hook.append("jingrow.tests.test_hooks.custom_has_permission")

		hooks.has_permission["*"] = wildcard_has_permission_hook

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

		# Init User and Address
		username = "test@example.com"
		user = jingrow.get_pg("User", username)
		user.add_roles("System Manager")
		address = jingrow.new_pg("Address")

		# Create Note
		note = jingrow.new_pg("Note")
		note.public = 1

		# Test!
		self.assertTrue(jingrow.has_permission("Address", pg=address, user=username))
		self.assertTrue(jingrow.has_permission("Note", pg=note, user=username))

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

		note.flags.dont_touch_me = True
		self.assertFalse(jingrow.has_permission("Note", pg=note, user=username))

	def test_ignore_links_on_delete(self):
		email_unsubscribe = jingrow.get_pg(
			{"pagetype": "Email Unsubscribe", "email": "test@example.com", "global_unsubscribe": 1}
		).insert()

		event = jingrow.get_pg(
			{
				"pagetype": "Event",
				"subject": "Test Event",
				"starts_on": "2022-12-21",
				"event_type": "Public",
				"event_participants": [
					{
						"reference_pagetype": "Email Unsubscribe",
						"reference_pagename": email_unsubscribe.name,
					}
				],
			}
		).insert()
		self.assertRaises(jingrow.LinkExistsError, email_unsubscribe.delete)

		event.event_participants = []
		event.save()

		todo = jingrow.get_pg(
			{
				"pagetype": "ToDo",
				"description": "Test ToDo",
				"reference_type": "Event",
				"reference_name": event.name,
			}
		)
		todo.insert()

		event.delete()


class TestAPIHooks(JingrowAPITestCase):
	def test_auth_hook(self):
		with patch_hooks({"auth_hooks": ["jingrow.tests.test_hooks.custom_auth"]}):
			site_url = jingrow.utils.get_site_url(jingrow.local.site)
			response = self.get(
				site_url + "/api/action/jingrow.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(pg, ptype, user):
	if pg.flags.dont_touch_me:
		return False


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


class CustomToDo(ToDo):
	pass
