#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: create group in azure, add member, modify group
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-office365

import time

import univention.testing.strings as uts
import univention.testing.ucr as ucr_test
import univention.testing.udm as udm_test
import univention.testing.utils as utils
from univention.config_registry import handler_set

from helpers.office365_test_helpers import listener_attributes_data, udm_user_args, check_udm2azure_user
from univention.office365.azure_handler import AzureHandler, ResourceNotFoundError
from univention.office365.listener import Office365Listener


with utils.AutomaticListenerRestart():
	with udm_test.UCSTestUDM() as udm:
		with ucr_test.UCSTestConfigRegistry() as ucr:
			ah = AzureHandler(ucr, "ucs-test")
			class _listener(object):
				configRegistry = ucr
			ol = Office365Listener(_listener(), "ucs-test", listener_attributes_data, {}, "dn")

			handler_set(["office365/groups/sync=yes", "office365/debug/werror=yes"])
			utils.restart_listener()

			print("*** Creating group (not synced to Azure AD yet)...")
			group_name = uts.random_name()
			description = uts.random_string()
			group_dn = udm.create_object(
				"groups/group",
				set=dict(
					name=group_name,
					description=description
				),
				position="cn=groups,{}".format(ucr.get("ldap/base")),
				check_for_drs_replication=True
			)

			print("*** Creating office365-activated user in group, should trigger sync of group...")
			user_args = udm_user_args(ucr, minimal=True)
			user_args["set"]["UniventionOffice365Enabled"] = 1
			user_args["append"]["groups"] = [group_dn]
			user_dn, username = udm.create_user(**user_args)
			time.sleep(5)

			print("*** Checking that user was created...")
			udm_user = ol.udm.get_udm_user(user_dn)
			user_id = udm_user.get("UniventionOffice365ObjectID")
			if not user_id:
				utils.fail("User was not created properly (no UniventionOffice365ObjectID).")
			fake_listener_new = dict(
				entryUUID=[udm_user.dn],
				univentionOffice365ObjectID=[udm_user["UniventionOffice365ObjectID"]]
			)
			azure_user = ol.get_user(fake_listener_new)
			success, errors = check_udm2azure_user(user_args, azure_user, complete=False)
			if success:
				print("*** all attributes were synced correctly")
			else:
				utils.fail("One or more properties were not synced correctly:\n{}".format("\n".join(map(str, errors))))

			print("*** Checking that group was created...")
			udm_group = ol.udm.get_udm_group(group_dn)
			group_id = udm_group.get("UniventionOffice365ObjectID")
			if not group_id:
				utils.fail("Group was not created properly (no UniventionOffice365ObjectID in UDM object).")
			azure_group1 = ah.list_groups(objectid=group_id)
			if not group_id == azure_group1["objectId"]:
				utils.fail("Could not find group in Azure AD.")

			print("*** Checking membership of user in azure group...")
			members = ah.get_groups_direct_members(group_id)["value"]
			members = ah.directory_object_urls_to_object_ids(members)
			if len(members) != 1 or user_id not in members:
				utils.fail("Failed to add user to group. members={}".format(members))

			print("*** Removing user from group...")
			udm.modify_object(
				"groups/group",
				dn=group_dn,
				remove=dict(
					users=[user_dn]
				),
				check_for_drs_replication=True
			)
			time.sleep(5)

			print("*** Checking that azure group was deleted...")
			try:
				azure_group2 = ah.list_groups(objectid=group_id)
				if not azure_group2["mailNickname"].startswith("ZZZ_deleted_"):
					utils.fail("Group was not removed.")
			except ResourceNotFoundError:
				pass

			print("*** All went well.")
