#goal: standalone function that recieves a boolean/rpn string and returns a list of filenames
#also needs access to the nudaDBTable file

import pickle

def boolean_operator(listA, listB, operator):
    setA = set(listA) #convert to sets here? or work with sets from the start?
    setB = set(listB)
    if operator=='and':
        return list(setA.intersection(setB))
    elif operator=='or':
        return list(setA.union(setB))
    elif operator=='not':   #this is really the binary operator: 'A (and not) B'
        return list(setA.difference(setB))

def parse_postfix(searchString):
    #split searchString by delimiter (-)
    searchList = searchString.split('-')
    print('searchList: ', searchList)
    #replace each string in the list with its search result list, unless it's an operator
    with open("../tags.pickle","rb") as pickleFile:
        tagDict = pickle.load(pickleFile)
        for i in range(len(searchList)):
            if searchList[i] not in ['and','or','not']:
                searchList[i] = tagDict[searchList[i]]
    print('searchList: ', searchList)
    #walk through searchList, executing operators when encountered
    cursor = 0
    while len(searchList)>1:
        print('searchList: ', searchList)
        if cursor>=len(searchList): #reached the end and ran out of operators, 'and' everything that remains
            searchList[0] = boolean_operator(searchList[0], searchList.pop(1), 'and')
        elif searchList[cursor] in ['and','or','not']:
            searchList[cursor-2] = boolean_operator(searchList[cursor-2], searchList.pop(cursor-1), searchList.pop(cursor-1))
            cursor -= 2 #adjust for both pops
        cursor += 1
    return searchList[0]


if __name__ == '__main__':
    result = parse_postfix('apollo-fiona-and')
    print("OUTPUT: ", result)
