"""
Helper utilities for browsing the respository of test files.

from PRConfig.TestFileDB import test_file_db

browseTestFiles(test_file_db)

Lets you neatly browse through the available test files to see what's there.
"""

from PRConfig.TestFileObjects import testfiles

##################### Useful functions ################

def browseTestFiles(database,pseudodirectory=""):
    """
    browse through the available test files logically with a directory-like structure.
    pseudodirectory: a string looks like a directory: Qualifier/value/Qualifier2/value2 ...
    """
    
    #understand pseudodirectory as dictionary:
    qual_dict, dangling = __dictfromdir__(pseudodirectory)
    
    seldb=__selectwithdict__(database,qual_dict)
    
    diff_quals=[]
    seenquals=[]
    if dangling is not None and (dangling.lower()=="all" or dangling.lower()=="any"):
        print "Found",len(seldb), "testfile entries, displaying all"
        for entry in seldb:
            print
            print "------", entry,"------"
            print seldb[entry]
        return True
    
    #if there's no dangling part, I'm going to display the different qualifiers
    #compile list of qualifiers which show differences
    if dangling is None or not len(dangling):
        #print "categorizing", len(seldb)
        for qual in testfiles.__known_qualifiers__:
            if qual in diff_quals:
                break
            #don't bother for certain qualifiers
            if qual in ["Date", "QMTests"]:
                continue
            inval=None
            for entry in seldb:
                if inval is None:
                    if qual in seldb[entry].qualifiers:
                        #if type(qual) is str or type(qual) is bool:
                        seenquals.append(qual)
                        inval=seldb[entry].qualifiers[qual]
                        #print "found initial ", qual, inval, entry
                else:
                    if qual in seldb[entry].qualifiers:
                        if seldb[entry].qualifiers[qual]!=inval:
                            #print "found diff for ", qual, inval, entry
                            diff_quals.append(qual)
                            break
        #if there are no differences, display all the data
        if not len(diff_quals):
            print "Found", len(seldb), "testfile entries"
            for entry in seldb:
                print "------", entry,"------"
                print seldb[entry]
            return True
        #else display the subdirectories to look at
        print "Found", len(seldb), "testfile entries, subselect please or add '/all'"
        for d in diff_quals:
            print d+"/"
        return False
    
    #if there's a dangling part, I'm going to display the possible qualifiers
    seen=[]
    for entry in seldb:
        if dangling in seldb[entry].qualifiers:
            if seldb[entry].qualifiers[dangling] not in seen:
                seen.append(seldb[entry].qualifiers[dangling])
        else:
            if "None" not in seen:
                seen.append("None")
    print "Found",len(seldb), "entries, categorizing by", dangling
    for s in seen:
        print str(s)+"/"
    return False


##################### Internal functions ################


def __dictfromdir__(dir):
    """Parse a pseudo directory into a dictionary of database queries...
    """
    #print "parsing", dir
    dir=dir.lstrip("/").rstrip("/")
    mydict={}
    dangling=None
    if len(dir)==0:
        #print "parsed", mydict, dangling
        return mydict, dangling
    dir=dir.split("/")
    if len(dir)==0:
        #print "parsed", mydict, dangling
        return mydict, dangling
    if len(dir)%2!=0:
        dangling=dir[-1]
        dir=dir[:-1]
    if len(dir)==0:
        #print "parsed", mydict, dangling
        return mydict, dangling
    i=0
    while i+1<len(dir):
        mydict[dir[i]]=dir[i+1]
        i=i+2
    #print "parsed", mydict, dangling
    return mydict, dangling

def __selectwithdict__(db,qual_dict):
    """
    helper fuction, subselect within the database
    """
    retdb=db
    print "selecting", qual_dict
    #return a copy of the original dictionary
    if len(qual_dict)==0:
        for key in db:
            retdb[key]=db[key]
        #print "returning", len(retdb), "entries"
        return retdb
    #return a subselection of the original dictionary
    #"None" is interpreted as no entry for a given qualifier
    for key in qual_dict:
        retdb=__selectwithpair__(retdb,key,qual_dict[key])
    #print "returning", len(retdb), "entries"
    return retdb

def __selectwithpair__(db, key, val):
    retdb={}
    for entry in db:
        if (key in db[entry].qualifiers and val==str(db[entry].qualifiers[key])) or (val=="None" and key not in db[entry].qualifiers):
            retdb[entry]=db[entry]
    return retdb
