import ldap3
import logging
from ldap3.core.exceptions import LDAPBindError

logger = logging.getLogger(__name__)


def authentication(username, password):
    # no empty passwords
    if password is None or password.strip() == "":
        return None

    # username format
    new_username = "uid={username},ou=user,dc=fet,dc=htu,dc=tuwien,dc=ac,dc=at"
    userdn = new_username.format(username=username)

    server_uri = "ldap://juri.fet.htu.tuwien.ac.at"
    server = ldap3.Server(server_uri, port=389, use_ssl=True)

    has_user = False

    try:
        conn = ldap3.Connection(server, user=userdn, password=password, auto_bind=True)
        conn.search("dc=fet,dc=htu,dc=tuwien,dc=ac,dc=at", "(objectclass=person)")
        for user in sorted(conn.entries):
            if ("DN: uid=" + str(username.lower())) in str(user):
                has_user = True
    except LDAPBindError as e:
        logger.info("Username does not exist. Error: {}".format(e))
        username = None
    except Exception as e:
        logger.info("Connection to server lost. Error: {}".format(e))
        username = None

    if not has_user:
        username = None

    return username
