# Copyright (c) 2023, JINGROW
# See license.txt

import jingrow
from jingrow.tests.utils import JingrowTestCase

from jcloud.jcloud.pagetype.jcloud_user_permission.jcloud_user_permission import (
	has_user_permission,
)
from jcloud.jcloud.pagetype.site.test_site import create_test_site
from jcloud.jcloud.pagetype.team.test_team import create_test_team


class TestJcloudUserPermission(JingrowTestCase):
	def setUp(self):
		self.team = create_test_team()
		self.site = create_test_site(subdomain="testpermsite")

	def tearDown(self):
		jingrow.set_user("Administrator")
		jingrow.db.rollback()

	def test_jcloud_user_permission(self):
		self.assertFalse(has_user_permission("Site", self.site.name, "jcloud.api.site.login"))

		jingrow.get_pg(
			pagetype="Jcloud User Permission",
			type="User",
			user=jingrow.session.user,
			document_type="Site",
			document_name=self.site.name,
			action="jcloud.api.site.login",
		).insert(ignore_permissions=True)

		self.assertTrue(has_user_permission("Site", self.site.name, "jcloud.api.site.login"))
		self.assertFalse(
			has_user_permission("Site", self.site.name, "jcloud.api.site.migrate")
		)

	def test_jcloud_group_permission(self):
		group = jingrow.get_pg(
			pagetype="Jcloud Permission Group", team=self.team.name, title="Test Group"
		)
		group.append("users", {"user": jingrow.session.user})
		group.insert(ignore_permissions=True)

		jingrow.get_pg(
			pagetype="Jcloud User Permission",
			type="Group",
			group=group.name,
			document_type="Site",
			document_name=self.site.name,
			action="jcloud.api.site.overview",
		).insert(ignore_permissions=True)

		self.assertTrue(
			has_user_permission(
				"Site", self.site.name, "jcloud.api.site.overview", groups=[group.name]
			)
		)
		self.assertFalse(
			has_user_permission(
				"Site", self.site.name, "jcloud.api.site.migrate", groups=[group.name]
			)
		)

	def test_jcloud_config_permission(self):
		perms = {
			"global": {
				"Site": {"*": "jcloud.api.site.login"},
			},
			"restricted": {"Site": {"test.jingrow.dev": "jcloud.api.site.migrate"}},
		}
		jingrow.get_pg(
			pagetype="Jcloud User Permission",
			type="Config",
			config=jingrow.as_json(perms),
			user=jingrow.session.user,
		).insert(ignore_permissions=True)

		self.assertTrue(has_user_permission("Site", self.site.name, "jcloud.api.site.login"))
		self.assertFalse(
			has_user_permission("Site", "sometest.jingrow.dev", "jcloud.api.site.restore")
		)
		self.assertFalse(
			has_user_permission("Site", "test.jingrow.dev", "jcloud.api.site.migrate")
		)
		self.assertTrue(
			has_user_permission("Site", "test.jingrow.dev", "jcloud.api.site.login")
		)
