#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: check create, retrieve, login, remove
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-ox

import univention.testing.udm as testing_udm
import univention.testing.ucr as testing_ucr
import univention.testing.strings as uts
import univention.testing.utils as utils
from univention.ox.api.http.http_api_client import OXHttpApi, NotFoundError, LoginError, AttributeSyncError
from univention.ox.wait_for_ox_server import wait_for_ox_server
from univention.ox.oxlistener import OxListener
from essential.common import OXTestEmptyQueue


wait_for_ox_server()
with testing_udm.UCSTestUDM() as udm, testing_ucr.UCSTestConfigRegistry() as ucr, OXTestEmptyQueue():
	default_context_id = OxListener.get_default_context_id()
	credentials = OxListener.get_credentials(default_context_id)
	client = OXHttpApi(credentials)

	print('*** Creating OX user account...')
	user_password = uts.random_string()
	mail_domain = ucr['mail/hosteddomains'].split()[0]
	user_dn, username = udm.create_user(
		mailPrimaryAddress='{}@{}'.format(uts.random_username(), mail_domain),
		password=user_password,
		isOxUser='OK')

	print('*** Reading and checking OX user account...')
	try:
		client.compare_ldap_and_ox_user(username)
	except NotFoundError as exc:
		utils.fail('{}\nList of all users:\n{}'.format(str(exc), client.list_users()))
	except AttributeSyncError as exc:
		utils.fail(str(exc))

	print('*** Trying to login with OX user account...')
	try:
		OXHttpApi(username, user_password)
	except LoginError as exc:
		utils.fail('Could not login with user "{}": {}'.format(username, str(exc)))
	print('*** OK: logged in with user "{}".'.format(username))

	print('*** Deleting OX user account...')
	udm.remove_object('users/user', dn=user_dn)
	try:
		oid = client.username_to_id(username)
	except NotFoundError:
		print('*** OK: user not found in OX-DB anymore.')
	else:
		utils.fail('User still exists in OX-DB.')
