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

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 univention.googleapps.handler import GappsHandler
from univention.googleapps.listener import GoogleAppsListener
from helpers.gapps_test_helpers import udm_user_args, check_udm2google_user, listener_attributes_data, setup_domain


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

gl = GoogleAppsListener(None, listener_attributes_data, {})
gh = GappsHandler(None)

with utils.AutomaticListenerRestart() as alr:
	with udm_test.UCSTestUDM() as udm:
		with ucr_test.UCSTestConfigRegistry() as ucr:
			print "*** Setting UCRs for maximum property sync..."
			handler_unset(["google-apps/attributes/anonymize", "google-apps/attributes/never"])
			handler_set([
				"google-apps/attributes/mapping/name=familyName=%sn,givenName=%givenName,fullName=%displayName",
				"google-apps/attributes/mapping/phones/1=type=home,value=%homePhone",
				"google-apps/attributes/mapping/phones/2=type=mobile,value=%mobile",
				"google-apps/attributes/mapping/phones/3=type=pager,value=%pager",
				"google-apps/attributes/mapping/phones/4=type=work,value=%telephoneNumber",
				"google-apps/attributes/mapping/addresses/1=type=home,formatted=%homePostalAddress",
				"google-apps/attributes/mapping/addresses/2=type=work,locality=%l,postalCode=%postalCode,countryCode=%st,streetAddress=%street,extendedAddress=%departmentNumber",
				"google-apps/attributes/mapping/addresses/3=type=custom,customType=locality,locality=%roomNumber",
				"google-apps/attributes/mapping/emails/1=type=work,address=%mail",
				"google-apps/attributes/mapping/emails/2=type=other,address=%mailAlternativeAddress",
				"google-apps/attributes/mapping/organizations=primary=True,name=%o,description=%employeeType",
				"google-apps/attributes/mapping/relations=type=custom,customType=secretary,value=%secretary",
				"google-apps/attributes/mapping/externalIds=type=organization,value=%employeeNumber",
				"google-apps/debug/werror=yes",
			])
			utils.restart_listener()

			maildomain = gh.get_primary_domain_from_disk()
			setup_domain(maildomain, udm, ucr)

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

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

			user_args3 = dict(set=dict(), append=dict())
			for key in ["street", "title"]:
				user_args3["set"][key] = user_args1["set"].pop(key)
			for key in ["homeTelephoneNumber", "mobileTelephoneNumber", "secretary"]:
				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)

			print "*** Checking that user was created (UniventionGoogleAppsObjectID in UDM object)..."
			udm_user = gl.get_udm_user(user_dn)
			if not udm_user.get("UniventionGoogleAppsObjectID"):
				utils.fail("User was not created.")

			print "*** Checking sync of properties #0..."
			time.sleep(5)
			google_user = gh.get_user(udm_user["UniventionGoogleAppsObjectID"], projection="full")
			_test(user_args1, google_user, maildomain, False)

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

			print "*** Checking sync of properties #1..."
			time.sleep(5)
			google_user = gh.get_user(udm_user["UniventionGoogleAppsObjectID"], projection="full")
			_test(user_args2, google_user, maildomain, False)

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

			print "*** Checking sync of properties #2..."
			time.sleep(5)
			google_user = gh.get_user(udm_user["UniventionGoogleAppsObjectID"], projection="full")
			_test(user_args3, google_user, maildomain, False)

			print "*** Checking sync of all properties..."
			google_user = gh.get_user(udm_user["UniventionGoogleAppsObjectID"], projection="full")
			_test(user_args, google_user, maildomain, True)
