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

    server_uri = "ldap://juri.fet.htu.tuwien.ac.at"
    server = ldap3.Server(server_uri, port=389, use_ssl=True)
    userdn = f"uid={username},ou=user,dc=fet,dc=htu,dc=tuwien,dc=ac,dc=at"

    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 f"DN: uid={username}" in str(user):
                return username
    except LDAPBindError as e:
        logger.info(f"Username does not exist. Error: {e}")
    except Exception as e:
        logger.info(f"Connection to server lost. Error: {e}")

    logger.info(f"This username has been typed: '{username}'")
    return None
