#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: create and modify user in azure, check property-sync
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-office365

import copy
import time

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, handler_unset

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


def _test(udm_args, a_user, check_complete):
	success, errors = check_udm2azure_user(udm_args, a_user, check_complete)
	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))))

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

			print("*** Setting UCRs for maximum property sync...")
			to_unset = ["office365/attributes/anonymize", "office365/attributes/never",
				"office365/groups/sync", "office365/subscriptions/service_plan_names"]
			to_unset.extend([k.split("=")[0] for k, v in ucr.items() if k.startswith("office365/attributes/static/")])
			handler_unset(to_unset)
			handler_set([
				"office365/attributes/mapping/l=city",
				"office365/attributes/mapping/displayName=displayName",
				"office365/attributes/mapping/employeeType=jobTitle",
				"office365/attributes/mapping/givenName=givenName",
				"office365/attributes/mapping/mobile=mobile",
				"office365/attributes/mapping/mail=otherMails",
				"office365/attributes/mapping/mailAlternativeAddress=otherMails",
				"office365/attributes/mapping/mailPrimaryAddress=otherMails",
				"office365/attributes/mapping/postalCode=postalCode",
				"office365/attributes/mapping/roomNumber=physicalDeliveryOfficeName",
				"office365/attributes/mapping/st=usageLocation",
				"office365/attributes/mapping/street=streetAddress",
				"office365/attributes/mapping/sn=surname",
				"office365/attributes/mapping/telephoneNumber=telephoneNumber",
				"office365/attributes/sync=l,st,displayName,employeeType,givenName,mailPrimaryAddress,mobile,mailAlternativeAddress,mail,postalCode,roomNumber,st,street,sn,telephoneNumber",
				"office365/debug/werror=yes",
			])
			utils.restart_listener()

			user_args = udm_user_args(ucr, minimal=False)
			user_args["set"]["UniventionOffice365Enabled"] = 1
			user_args1 = copy.deepcopy(user_args)

			user_args2 = dict(set=dict(), append=dict())
			for key in ["city", "employeeType"]:
				user_args2["set"][key] = user_args1["set"].pop(key)
			user_args2["append"]["phone"] = user_args1["append"].pop("phone")

			user_args3 = dict(set=dict(), append=dict())
			for key in ["street", "country"]:
				user_args3["set"][key] = user_args1["set"].pop(key)
			for key in ["e-mail", "mailAlternativeAddress"]:
				user_args3["append"][key] = user_args1["append"].pop(key)

			print("*** Creating user with some properties...")
			user_dn, username = udm.create_user(check_for_drs_replication=True, **user_args1)
			time.sleep(5)

			print("*** Checking that user was created (UniventionOffice365ObjectID in UDM object)...")
			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).")

			print("*** Checking sync of properties #0...")
			fake_listener_new = dict(
				entryUUID=[udm_user.dn],
				univentionOffice365ObjectID=[user_id]
			)
			azure_user = ol.get_user(fake_listener_new)
			_test(user_args1, azure_user, check_complete=False)

			print("*** Adding more properties to user #1...")
			udm.modify_object(modulename="users/user", dn=user_dn, **user_args2)
			time.sleep(5)

			print("*** Checking sync of properties #1...")
			azure_user = ol.get_user(fake_listener_new)
			_test(user_args2, azure_user, check_complete=False)

			print("*** Adding more properties to user #2...")
			udm.modify_object(modulename="users/user", dn=user_dn, **user_args3)
			time.sleep(5)

			print("*** Checking sync of properties #2...")
			azure_user = ol.get_user(fake_listener_new)
			_test(user_args3, azure_user, check_complete=False)

			print("*** Checking sync of all properties...")
			azure_user = ol.get_user(fake_listener_new)
			_test(user_args, azure_user, check_complete=True)
