# --- BEGIN COPYRIGHT BLOCK ---
# Copyright (C) 2015 Red Hat, Inc.
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# --- END COPYRIGHT BLOCK ---

""" Testing basic functionalities of DirSrv


"""
import ldap
import lib389
from lib389 import DirSrv
from lib389 import NoSuchEntryError
from ldap import *
# from nose.tools import *
from . import config
from .config import *

conn = None
added_entries = None


def setup():
    global conn
    try:
        conn = DirSrv(**config.auth)
        conn.verbose = True
        conn.added_entries = []
    except SERVER_DOWN as e:
        log.error("To run tests you need a working 389 instance %s" %
                  config.auth)
        raise e


def tearDown():
    global conn

    # reduce log level
    conn.config.loglevel([lib389.LOG_CACHE])
    conn.config.loglevel([256], service='access')

    for e in conn.added_entries:
        try:
            conn.delete_s(e)
        except ldap.NO_SUCH_OBJECT:
            log.warn("entry not found %r" % e)


def bind_test():
    print ("conn: %s" % conn)


def setupBindDN_UID_test():
    user = {
        'binddn': 'uid=rmanager1,cn=config',
        'bindpw': 'password'
    }
    e = conn.setupBindDN(**user)
    conn.added_entries.append(e.dn)

    assert e.dn == user['binddn'], "Bad entry: %r " % e
    expected = conn.getEntry(user['binddn'], ldap.SCOPE_BASE)
    assert entry_equals(
        e, expected), "Mismatching entry %r vs %r" % (e, expected)


def setupBindDN_CN_test():
    user = {
        'binddn': 'cn=rmanager1,cn=config',
        'bindpw': 'password'
    }
    e = conn.setupBindDN(**user)
    conn.added_entries.append(e.dn)
    assert e.dn == user['binddn'], "Bad entry: %r " % e
    expected = conn.getEntry(user['binddn'], ldap.SCOPE_BASE)
    assert entry_equals(
        e, expected), "Mismatching entry %r vs %r" % (e, expected)


def setupChangelog_default_test():
    e = conn.replica.changelog()
    conn.added_entries.append(e.dn)
    assert e.dn, "Bad changelog entry: %r " % e
    assert e.getValue('nsslapd-changelogdir').endswith("changelogdb"), \
        "Mismatching entry %r " % e.data.get('nsslapd-changelogdir')
    conn.delete_s("cn=changelog5,cn=config")


def setupChangelog_test():
    e = conn.replica.changelog(dbname="mockChangelogDb")
    conn.added_entries.append(e.dn)
    assert e.dn, "Bad changelog entry: %r " % e
    assert e.getValue('nsslapd-changelogdir').endswith("mockChangelogDb"), \
        "Mismatching entry %r " % e.data.get('nsslapd-changelogdir')
    conn.delete_s("cn=changelog5,cn=config")


def setupChangelog_full_test():
    e = conn.replica.changelog(dbname="/tmp/mockChangelogDb")
    conn.added_entries.append(e.dn)

    assert e.dn, "Bad changelog entry: %r " % e
    expect(e, 'nsslapd-changelogdir', "/tmp/mockChangelogDb")
    conn.delete_s("cn=changelog5,cn=config")


# @raises(NoSuchEntryError)
def getMTEntry_missing_test():
    e = conn.getMTEntry('o=MISSING')
    return e


def getMTEntry_present_test():
    suffix = 'o=addressbook16'
    bename = 'addressbookd16db'
    backendEntry, dummy = conn.backend.add(suffix, benamebase=bename)
    suffixEntry = conn.backend.setup_mt(suffix, bename)

    e = conn.getMTEntry(suffix)

    conn.backend.delete(bename)
    conn.delete_s(suffixEntry.dn)
    assert e, "Entry should be present %s" % suffix
