import pytest
from lib389.topologies import topology_st as topo
from lib389.idm.user import UserAccount, UserAccounts
from lib389._constants import DEFAULT_SUFFIX
from lib389.pwpolicy import PwPolicyManager


def create_user(topo, uid, cn, sn, givenname, userpassword, gid):
    user = UserAccounts(topo.standalone, DEFAULT_SUFFIX).create(properties={
        'uid': uid,
        'cn': cn,
        'sn': sn,
        'givenname': givenname,
        'mail': f'{uid}@example.com',
        'userpassword': userpassword,
        'homeDirectory': f'/home/{uid}',
        'uidNumber': gid,
        'gidNumber': gid
    })
    return user


def test_change_pw(topo):
 
    topo.standalone.config.set('nsslapd-auditlog-logging-enabled', 'on')
    topo.standalone.config.set('nsslapd-auditfaillog-logging-enabled', 'on')

    create_user(topo, 'tuser', 'tuser', 'user', 'test', 'password', '1111')
    pwp = PwPolicyManager(topo.standalone)
    people = pwp.create_subtree_policy(f'ou=People,{DEFAULT_SUFFIX}', {'passwordmustchange': 'on'})
    # Change user's password by DM
    password = 'password_set_by_DM'
    UserAccount(topo.standalone, f'uid=tuser,ou=people,{DEFAULT_SUFFIX}').replace('userpassword', password)
    user = UserAccount(topo.standalone, f'uid=tuser,ou=people,{DEFAULT_SUFFIX}')
    # Bind should be successful
    conn = user.bind(password)
    UserAccount(topo.standalone, f'uid=tuser,ou=people,{DEFAULT_SUFFIX}').set('userPassword', 'my_new_password')


if __name__ == "__main__":
    CURRENT_FILE = os.path.realpath(__file__)
    pytest.main("-s -v %s" % CURRENT_FILE)
