# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

import jingrow
from jingrow.core.pagetype.role.role import get_info_based_on_role
from jingrow.tests.utils import JingrowTestCase

test_records = jingrow.get_test_records("Role")


class TestUser(JingrowTestCase):
	def test_disable_role(self):
		jingrow.get_pg("User", "test@example.com").add_roles("_Test Role 3")

		role = jingrow.get_pg("Role", "_Test Role 3")
		role.disabled = 1
		role.save()

		self.assertTrue("_Test Role 3" not in jingrow.get_roles("test@example.com"))

		role = jingrow.get_pg("Role", "_Test Role 3")
		role.disabled = 0
		role.save()

		jingrow.get_pg("User", "test@example.com").add_roles("_Test Role 3")
		self.assertTrue("_Test Role 3" in jingrow.get_roles("test@example.com"))

	def test_change_desk_access(self):
		"""if we change desk acecss from role, remove from user"""
		jingrow.delete_pg_if_exists("User", "test-user-for-desk-access@example.com")
		jingrow.delete_pg_if_exists("Role", "desk-access-test")
		user = jingrow.get_pg(
			dict(pagetype="User", email="test-user-for-desk-access@example.com", first_name="test")
		).insert()
		role = jingrow.get_pg(dict(pagetype="Role", role_name="desk-access-test", desk_access=0)).insert()
		user.add_roles(role.name)
		user.save()
		self.assertTrue(user.user_type == "Website User")
		role.desk_access = 1
		role.save()
		user.reload()
		self.assertTrue(user.user_type == "System User")
		role.desk_access = 0
		role.save()
		user.reload()
		self.assertTrue(user.user_type == "Website User")

	def test_get_users_by_role(self):
		role = "System Manager"
		sys_managers = get_info_based_on_role(role, field="name")

		for user in sys_managers:
			self.assertIn(role, jingrow.get_roles(user))
