import ldap3
import sys
from config import config
from ldap3 import Server, Connection, ObjectDef, Reader, ALL, SUBTREE, ALL_ATTRIBUTES
from ldap3.core import exceptions


LDAP_SERVER = config['ldap']['server']
LDAP_PASSWORD = config['ldap']['admin_password']
LDAP_USER = config['ldap']['admin_dn'] 
LDAP_PORT = int(config['ldap']['ldap_port'])

# Create the Server object with the given address.
server = Server(LDAP_SERVER, LDAP_PORT, get_info=ALL)
#Create a connection object, and bind with the given DN and password.
try: 
                conn = Connection(server, LDAP_USER, LDAP_PASSWORD, auto_bind=True)
                print('LDAP Bind Successful.')
                # Perform a search for a pre-defined criteria.
                # Mention the search filter / filter type and attributes.
                conn.search('ou=customer,dc=ungleich,dc=ch', '(&(!({}={})))'.format('mail','*@ungleich.ch') , attributes=['uid','mail'])
                #conn.search('ou=customer,dc=ungleich,dc=ch', '(objectClass=*)' , attributes=['uid','mail'])
                # Print the resulting entriesn.
                #for entry in conn.entries:
                       #print(entry.uid, entry.mail)
                vm_list = conn
except exceptions.LDAPException as err:
                sys.exit(f'LDAP Error: {err}')