#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: check create, retrieve, remove of a resource
## tags: [apptest]
## exposure: dangerous
## packages:
##   - python3-univention-ox-soap-api-client

import time
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.wait_for_ox_server import wait_for_ox_server
from univention.ox.listener_tools import default_context
import univention.ox.soap.backend  # noqa
from univention.ox.backend_base import get_ox_integration_class
from essential.common import OXTestEmptyQueue, OXTestEnv


wait_for_ox_server()
with testing_udm.UCSTestUDM() as udm, testing_ucr.UCSTestConfigRegistry() as ucr, OXTestEnv() as oxenv, OXTestEmptyQueue():
	Resource = get_ox_integration_class('SOAP', 'Resource')
	name = uts.random_username()
	mail_domain = ucr['mail/hosteddomains'].split()[0]
	res = Resource(
		context_id=default_context,
		name=name,
		email='{}@{}'.format(uts.random_username(), mail_domain)
	)
	print('*** Creating OX resource via SOAP: {!r}...'.format(res))
	res_id = res.create()

	print('*** Reading and checking resource...')
	oxenv.check_if_resource_exists_via_csv(default_context, name)
	oxenv.check_if_resource_exists_via_soap(default_context, name)

	print('*** Deleting resource via SOAP...')
	res.remove()

	print('*** Checking if resource was deleted...')
	exists1 = oxenv.check_if_resource_exists_via_csv(default_context, name, raise_exception=False)
	exists2 = oxenv.check_if_resource_exists_via_soap(default_context, name, raise_exception=False)
	if exists1 or exists2:
		utils.fail('Resource still exists.')

	name = uts.random_username()
	print('*** Creating OX resource {!r} via UDM...'.format(name))
	oxenv.create_resource_via_udm(udm, name)

	print('*** Reading and checking resource...')
	oxenv.check_if_resource_exists_via_csv(default_context, name)
	oxenv.check_if_resource_exists_via_soap(default_context, name)

	print('*** Deleting resource via UDM (exiting UCSTestUDM context manager)...')
utils.wait_for_replication()

print('*** Checking if resource was deleted...')
exists1 = oxenv.check_if_resource_exists_via_csv(default_context, name, raise_exception=False)
exists2 = oxenv.check_if_resource_exists_via_soap(default_context, name, raise_exception=False)
if exists1 or exists2:
	utils.fail('Resource still exists.')
