#!/usr/share/ucs-test/runner pytest-3
## desc: Test univentionObjectIdentifier
## tags: [udm,apptest]
## roles: [domaincontroller_master]
## exposure: careful
## packages:
##   - univention-config
##   - univention-directory-manager-tools

import subprocess
import time
import uuid

import pytest

from univention.testing import utils
from univention.testing.ucr import UCSTestConfigRegistry


@pytest.fixture
def assert_autogenerated_univentionObjectIdentifier(lo):
    def _assert(dn: str):
        search_result = lo.search(base=dn)
        assert len(search_result) == 1
        properties = search_result[0][1]
        assert "univentionObjectIdentifier" in properties.keys()
        uuid.UUID(properties["univentionObjectIdentifier"][0].decode("utf-8"))
    return _assert


class TestUniventionObjectIdentifier:
    @pytest.fixture(scope="class", autouse=True)
    def activate_univentionObjectIdentifier(self):
        with UCSTestConfigRegistry() as ucr:
            ucr.handler_set(['directory/manager/object-identifier/autogeneration=true'])
            subprocess.run(["systemctl", "restart", "univention-directory-manager-rest.service"], check=True)
            # Wait for the UDM REST API to be available
            time.sleep(2)
            yield

    def test_user_explicitly_set_univentionObjectIdentifier(self, udm):
        test_identifier = str(uuid.uuid4())
        user = udm.create_user(univentionObjectIdentifier=test_identifier)[0]
        utils.verify_ldap_object(user, {"univentionObjectIdentifier": [test_identifier.encode("UTF-8")]}, retry_count=0)

    def test_user_autogenerated_univentionObjectIdentifier(self, udm, assert_autogenerated_univentionObjectIdentifier):
        user = udm.create_user()[0]

        assert_autogenerated_univentionObjectIdentifier(user)

    def test_group_explicitly_set_univentionObjectIdentifier(self, udm):
        """Create groups/group"""
        test_identifier = str(uuid.uuid4())
        group = udm.create_group(univentionObjectIdentifier=test_identifier)[0]

        utils.verify_ldap_object(group, {"univentionObjectIdentifier": [test_identifier.encode("UTF-8")]}, retry_count=0)

    def test_group_autogenerated_univentionObjectIdentifier(self, udm, assert_autogenerated_univentionObjectIdentifier):
        group = udm.create_user()[0]

        assert_autogenerated_univentionObjectIdentifier(group)
