from phi.ldap.user import get_user_by_uid, get_all_users, \
                          add_user, delete_user_by_uid, delete_user

from phi.ldap.group import add_group_member, get_group_by_cn, get_all_groups


def test_connection(ldap_client):
    assert ldap_client.connection.closed is False
    assert ldap_client.connection.bound is True


def test_get_user_by_id(ldap_client):
    user = get_user_by_uid(ldap_client, 'conte_mascetti')
    assert user['uid'] == 'conte_mascetti'
    assert user['mail'] == 'rmascetti@autistici.org'


def test_get_all_users(ldap_client):
    users = get_all_users(ldap_client)
    # print(users)
    assert 'conte_mascetti' in [u['uid'] for u in users]


def test_add_delete_user(ldap_client):
    uid = 'rosa_rossi'
    cn = 'Rosa'
    sn = 'Rossi'
    mail = 'foo@autistici.org'
    password = 'changeme'

    add_user(ldap_client, uid, cn, sn, mail, password)

    user = get_user_by_uid(ldap_client, uid)
    assert user['uid'] == uid
    assert user['mail'] == mail

    delete_user(ldap_client, user)
    # print(user)

    user = get_user_by_uid(ldap_client, uid)
    assert user is None


def test_failing_add_user(ldap_client):
    uid = 'conte_mascetti'

    try:
        add_user(ldap_client, uid, 'name', 'surname', 'mail', 'pass')
    except:  # User alrady existing
        pass
    else:
        assert False

def test_failing_delete_user(ldap_client):
    uid = 'rosa_rossi'

    try:
        delete_user_by_uid(ldap_client, uid)
    except:  # User already not existing
        pass
    else:
        assert False


def test_get_all_groups(ldap_client):
    groups = get_all_groups(ldap_client)

    cns = [g['cn'] for g in groups]
    assert 'WikiUsers' in cns


def test_add_to_group(ldap_client):
    client = ldap_client

    group_cn = 'WikiUsers'
    member_uid = 'rosa_rossi'
    add_user(client, member_uid, 'name', 'surname', 'mail', 'pass')

    user = get_user_by_uid(client, member_uid)
    # print(user)

    group = get_group_by_cn(client, group_cn)
    group_members = group['members']

    assert len(group_members) == 1
    # print(group_members)

    add_group_member(client, group, user)

    group = get_group_by_cn(client, group_cn)
    group_members = group['members']

    assert len(group_members) == 2
    assert user['uid'] in group_members

    # print(group_members)
    # print(user)

    delete_user(client, user)