# Copyright (c) 2021, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.installer import update_site_config
from jingrow.tests.utils import JingrowTestCase


class TestUserType(JingrowTestCase):
	def setUp(self):
		create_role()

	def test_add_select_perm_pagetypes(self):
		user_type = create_user_type("Test User Type")

		# select perms added for all link fields
		pg = jingrow.get_meta("Contact")
		link_fields = pg.get_link_fields()
		select_pagetypes = jingrow.get_all(
			"User Select Page Type", {"parent": user_type.name}, pluck="document_type"
		)

		for entry in link_fields:
			self.assertTrue(entry.options in select_pagetypes)

		# select perms added for all child table link fields
		link_fields = []
		for child_table in pg.get_table_fields():
			child_pg = jingrow.get_meta(child_table.options)
			link_fields.extend(child_pg.get_link_fields())

		for entry in link_fields:
			self.assertTrue(entry.options in select_pagetypes)

	def test_print_share_email_default(self):
		"""Test if print, share & email values default to 1. (for backward compatibility)"""
		# create user type with read, write permissions
		create_user_type("Test User Type")

		# check if print, share & email values are set to 1
		perm = jingrow.get_all("Custom PagePerm", filters={"role": "_Test User Type"}, fields=["*"])[0]

		self.assertTrue(perm.print == 1)
		self.assertTrue(perm.share == 1)
		self.assertTrue(perm.email == 1)

	def tearDown(self):
		jingrow.db.rollback()


def create_user_type(user_type):
	if jingrow.db.exists("User Type", user_type):
		jingrow.delete_pg("User Type", user_type)

	user_type_limit = {jingrow.scrub(user_type): 1}
	update_site_config("user_type_pagetype_limit", user_type_limit)

	pg = jingrow.get_pg(
		{
			"pagetype": "User Type",
			"name": user_type,
			"role": "_Test User Type",
			"user_id_field": "user",
			"apply_user_permission_on": "User",
		}
	)

	pg.append("user_pagetypes", {"document_type": "Contact", "read": 1, "write": 1})

	return pg.insert()


def create_role():
	if not jingrow.db.exists("Role", "_Test User Type"):
		jingrow.get_pg(
			{"pagetype": "Role", "role_name": "_Test User Type", "desk_access": 1, "is_custom": 1}
		).insert()
