import logging
import pytest
import os
import ldap
import time
from lib389 import Entry
from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES
from lib389._constants import *
from lib389.topologies import topology_st as topo

DEBUGGING = os.getenv("DEBUGGING", default=False)
if DEBUGGING:
    logging.getLogger(__name__).setLevel(logging.DEBUG)
else:
    logging.getLogger(__name__).setLevel(logging.INFO)
log = logging.getLogger(__name__)

TARGETATTR = "(targetattr = \"cn || createtimestamp || description || displayname || entryusn || gecos || gidnumber || givenname || homedirectory || initials || loginshell || manager || modifytimestamp || objectclass || sn || title || uid \")"
TARGETFILTER = "(targetfilter = \"(objectclass=posixaccount)\")"
RIGHTS = "(version 3.0;acl \"Read User Standard Attributes\";allow (compare,read,search) userdn = \"ldap:///anyone\";)"
ACI = TARGETATTR + TARGETFILTER + RIGHTS

ANONYM = "(targetattr!=\"userPassword || aci\")(version 3.0; acl \"Enable anonymous access\"; allow (read, search, compare) userdn=\"ldap:///anyone\";)"

PASSWD = 'password'
def test_ticket49617(topo):
    """Specify a test case purpose or name here

    :id: 0
    :setup: Standalone Instance
    :steps:
        1. Fill in test case steps here
        2. And indent them like this (RST format requirement)
    :expectedresults:
        1. Fill in the result that is expected
        2. For each test step
    """
    
    S = topo.standalone
    
    PEOPLE = "ou=People,%s" % SUFFIX
    S.modify_s(PEOPLE, [(ldap.MOD_REPLACE, 'aci', ACI.encode())])
    S.modify_s(SUFFIX, [(ldap.MOD_DELETE, 'aci', ANONYM.encode())])
    
    uid = b'my_user'
    users = UserAccounts(S, PEOPLE, rdn=None)
    user_props = TEST_USER_PROPERTIES.copy()
    user_props.update({'uid': uid, 'cn': uid, 'sn': '_%s' % uid, 'userpassword': PASSWD.encode(), 'description': b'value creation'})
    test_user = users.create(properties=user_props)
    
    Filter = "(uid=*)"
    
    S.bind(test_user.dn, PASSWD)
    ents = S.search_s(PEOPLE, ldap.SCOPE_SUBTREE, Filter)
    assert len(ents) == 1
    
    ents = S.search_s(PEOPLE, ldap.SCOPE_ONELEVEL, Filter)
    assert len(ents) == 1

    # If you need any test suite initialization,
    # please, write additional fixture for that (including finalizer).
    # Topology for suites are predefined in lib389/topologies.py.

    # If you need host, port or any other data about instance,
    # Please, use the instance object attributes for that (for example, topo.ms["master1"].serverid)

    if DEBUGGING:
        # Add debugging steps(if any)...
        pass


if __name__ == '__main__':
    # Run isolated
    # -s for DEBUG mode
    CURRENT_FILE = os.path.realpath(__file__)
    pytest.main(["-s", CURRENT_FILE])

