# -*- coding: utf-8 -*-
r"""Checks to be run within Valgrind

"""

from __future__ import print_function

import os

from _test_context import TESTDATADIR

import configmix


NUM = 10000
WITH_JAIL = True

DOTS = 1000


cfg = configmix.load(os.path.join(TESTDATADIR, "conf_perf.py"))

DEFAULT_DICT = {u"the": u"default"}


i = 1
while i <= NUM:

    tmp1 = cfg.getvarl(u"tree1", u"tree2", u"key8")
    tmp2 = cfg.getvarl_s(u"tree1", u"tree2", u"key8")
    tmp3 = cfg.getvar(u"tree1.tree2.key8")
    tmp4 = cfg.getvar_s(u"tree1.tree2.key8")

    try:
        tmp1 = cfg.getvarl(u"tree1", u"tree2", u"keyX")
    except KeyError:
        pass
    else:
        assert False
    try:
        tmp2 = cfg.getvarl_s(u"tree1", u"tree2", u"keyXX")
    except KeyError:
        pass
    else:
        assert False
    try:
        tmp3 = cfg.getvar(u"tree1.tree2.keyXXX")
    except KeyError:
        pass
    else:
        assert False
    try:
        tmp4 = cfg.getvar_s(u"tree1.tree2.keyXXXX")
    except KeyError:
        pass
    else:
        assert False

    tmp1 = cfg.getvarl_s(u"tree1", u"tree2", u"key10")
    # non-cacheable interpolation
    tmp2 = cfg.getvarl_s(u"tree1", u"tree2", u"key12")
    tmp3 = cfg.getvarl_s(u"tree1", u"tree2", u"key13")

    tmp1 = cfg.getvar_s(u"tree1.tree2.key10")
    # non-cacheable interpolation
    tmp2 = cfg.getvar_s(u"tree1.tree2.key12")
    tmp3 = cfg.getvar_s(u"tree1.tree2.key13")

    assert("key2" in cfg)
    assert((u"tree1", u"tree2", u"keyX") not in cfg)
    assert((u"tree1", u"tree2", u"key8") in cfg)

    tmp1 = cfg.getvarl(u"tree1", u"treeXXXX", default=DEFAULT_DICT)
    assert(tmp1 is DEFAULT_DICT)
    tmp2 = cfg.getvarl_s(u"tree1", u"treeXXXXXXX", default=DEFAULT_DICT)
    assert(tmp2 is DEFAULT_DICT)    
    tmp3 = cfg.getvar(u"treeXXXXXXXXXXX", default=DEFAULT_DICT)
    assert(tmp3 is DEFAULT_DICT)
    tmp4 = cfg.getvar_s(u"treeXXXXXXXXXXXXXXXXXXX", default=DEFAULT_DICT)
    assert(tmp4 is DEFAULT_DICT)

    if WITH_JAIL:
        jail = cfg.jailed(root=u"tree1.tree2")
        assert(u"key5" in jail)
        tmp1 = jail[u"key6"]
        tmp2 = jail[(u"key8",)]

        jail2 = cfg.jailed(rootpath=(u"tree1",))
        assert((u"tree2", u"key9") in jail2)
        tmp1 = jail2.getvarl_s(u"tree2")

        tmp1 = jail2.getvar(u"tree3")
        try:
            tmp2 = jail2.getvar_s(u"tree3")
        except KeyError:
            pass
        else:
            assert False

        try:
            tmp1 = jail2.getvar(u"treeXXXX")
        except KeyError:
            pass
        else:
            assert False

    if i % DOTS == 0:
        print(".", end='', flush=True)

    i += 1

jail = jail2 = None
tmp1 = tmp2 = tmp3 = tmp4 = None

print()
print("Done (loops: %d)." % (NUM,))
