#!/usr/bin/env python
import time
import coral
from coral.util.search.query import search
import coral.util.search.util as U
class QueryTest:
    def __init__(self,query):
        self.name=str(query.name)
        self.query_set=coral.Set()
        self.unique_matches = int(str(query.taggedValue.select(lambda tv: tv.name=="unique_matches")[0].dataValue))
        self.perm_matches = int(str(query.taggedValue.select(lambda tv: tv.name=="permutated_matches")[0].dataValue))
        
        
        for elem in query.ownedElement:
            self.query_set.append(elem)
            
    def match_in(self, target):
        matches=search(U.get_all_parts(self.query_set), target, self.query_set[0], False)
        print "Starting from", self.query_set[0]
        self.print_result(matches, self.unique_matches)
        
        matches=search(U.get_all_parts(self.query_set), target, None, True)
        self.print_result(matches, self.perm_matches)
        

    def print_result(self, matches, number):
        print "Found",len(matches),"matches in",self.name
        if len(matches) != number:
            print self.name+" failed with "+str(len(matches))+" results"
            num=1
            for m in matches:
                print "Result ",num
                num+=1
                for k,v in m.items():
                    print k,"->",v
            assert 0
        
test_time=time.time()
# load Target
prj=coral.loadDocument("bigQuery.xml")
target=None
queries=[]

for entry in prj.contents():
    if entry.name == "Target":
        print "found target:",entry.name
        target = entry
    if entry.oclIsKindOf(coral.lang.UML14.Model) and entry.name[:5] == "Query":
        print "found query",entry.name
        queries.append(QueryTest(entry))

print "Running searches"
start=time.time()

for query in queries:
    query.match_in(target)
print "Search time", time.time()-start
print "Test time", time.time()-test_time
# load many queries
# search many queries and check result
