## ------------------------------------------------------------------------
## iSiLK - A python-based graphical user interface for SiLK
## ------------------------------------------------------------------------
## Copyright (c) 2007-2008 Carnegie Mellon University. All Rights Reserved.
## ------------------------------------------------------------------------
## Authors: Andrew Kompanek (ajk@cert.org)
## ------------------------------------------------------------------------
## GNU General Public License (GPL) Rights pursuant to Version 2, June 1991
## Government Purpose License Rights (GPLR) pursuant to DFARS 252.225-7013
## ------------------------------------------------------------------------
## See the LICENSE file included in this distribution
## ------------------------------------------------------------------------
import wx
import silk
import tools
import resultset
import pdb

class QueryTool(tools.AnalysisTool):
    ''' kargs correspond to filter options supported by silk.query() '''
    def __init__(self, **kargs):
        tools.AnalysisTool.__init__(self, **kargs)
        
    def CanRun(parentResult):
        return True
    CanRun = staticmethod(CanRun)
            
    def GetCategory():
        return "Query"
    GetCategory = staticmethod(GetCategory)
    
    def _GetToolName():
        return "rwfilter (query)"
    _GetToolName = staticmethod(_GetToolName)
    
    def CreateDialog(parentResult, parent, title):
        return None
    CreateDialog = staticmethod(CreateDialog)

    def _GetResultClass(self):
        return resultset.QueryResult
        
    def _GetResultName(self):
        return "query"
        
    def _RunAnalysis(self, context, inputFile, outputFile):
        # Run initial fglob to see what files to expect
        files = silk.fglob(context, **self.opts)
        fileCount = len(files)
        #fileCount = 0
        #f = silk.fglob(context, **self.opts)
        #while True:
        #    l = f.readline()
        #    if not l:
        #        break
        #    if l[0] == "/":
        #        fileCount = fileCount + 1
        # Run rwfilter to do the actual query
        silk.query(context, fileCount, outputFile, **self.opts)
        # All tools need to generate an ascii file for display
        if "pmap-file" in self.opts:
            silk.cut(context, outputFile, outputFile+".asc",
                pmap_file=self.opts["pmap-file"])
        else:
            silk.cut(context, outputFile, outputFile+".asc")

    def _GetCommandLines(inputFileName, outputFileName, **kargs):
        return silk.build_query_command(False, "$output", kargs, inputFileName, commandsOnly=True)
    _GetCommandLines = staticmethod(_GetCommandLines)