#! /usr/bin/env python
#########################################################################
# This implements the createRDS standalone command in python
#########################################################################
import string
import sys
import Tkinter
from optparse import OptionParser

import diskCache
import LDASLogging
import LDASframe

tcl_interp = Tkinter.Tk().tk.eval

class createRDS(LDASframe.Options):
    def __init__(self):
        self.opts = LDASframe.Options( )
        self.server = diskCache.ServerInterface( )
        self.parser = OptionParser( )
        self.parser.add_option("--allow-short-frames",
                               action="store_true",
                               dest="allow_short_rames",
                               help="Specify if short frames are allowed to be generated")
        self.parser.add_option("--description",
                               action="store",
                               dest="description",
                               help="Specify the description portion of filename.")
        self.parser.add_option("--directory-output-frames",
                               action="store",
                               dest="directory_output_frames",
                               help="Directory holding the generated frame files")
        self.parser.add_option("--directory-output-md5sum",
                               action="store",
                               dest="directory_output_md5sum",
                               help="Directory holding md5sum values for the generated"
                                    " frame files")
        self.parser.add_option("--diskcache-host",
                               action="store",
                               dest="host",
                               help="Host number of the diskcache server")
        self.parser.add_option("--diskcache-port",
                               action="store",
                               dest="port",
                               type="int",
                               default=43833,
                               help="Port number of the diskcache server")
        self.parser.add_option("--fill-missing-data-valid-array",
                               action="store_true",
                               dest="fill_missing_data_valid_array",
                               help="Specify if the data valid array should be generated if it "
                               " missing from the input data")
        self.parser.add_option("--compression-type",
                               dest="compression_type",
                               help="Compression method to use when writing the frame to the stream")
        self.parser.add_option("--compression-level",
                               dest="compression_level",
                               type="int",
                               default=6,
                               help="Level of compression for compression methods that support it.")
        self.parser.add_option("--frame-files",
                               dest="frame_files",
                               help="A comma separated list of frame files")
        self.parser.add_option("--frame-query-tcl",
                               action="store",
                               dest="query_tcl",
                               help="Query for the diskcache server that has a TCL look and feel")
        self.parser.add_option("--frames-per-file",
                               dest="frames_per_file",
                               help="Specify the number of frames to store in each file")
        self.parser.add_option("--generate-frame-checksum",
                               action="store_true",
                               dest="generate_frame_checksum",
                               help="Specify if the frame checksum value should be generated")
        self.parser.add_option("--log-directory",
                               dest="log_directory",
                               help="Specify the directory to store logging information.")
        self.parser.add_option("--log-debug-level",
                               dest="log_debug_level",
                               type="int",
                               help="Specify the level of debugging information to generate.")
        self.parser.add_option("--seconds-per-frame",
                               dest="seconds_per_frame",
                               type="int",
                               help="Specify the number of seconds to store in each frame")
        self.parser.add_option("--without-history-record",
                               action="store_true",
                               dest="without_history_record",
                               help="Suppress the creation of the RDS history record"
                                    " in the output frames.")
        self.queries = []
        self.OFFSET_DESC = 0
        self.OFFSET_IFO = 1
        self.OFFSET_TIME_RANGE = 3
        self.OFFSET_CHANNELS = 4
        (self.opts, args) = self.parser.parse_args( sys.argv[1:], self.opts )
        print( "DEBUG: opts.host: %s opts.port: %d" 
               % ( self.opts.host, self.opts.port ) )
        self.server.Server( self.opts.host, self.opts.port )
        try:
            self.opts.log_debug_level
            print("DEBUG: Setting debug level to: %d"
                  %  (self.opts.log_debug_level))
            LDASLogging.setLogDebugLevel( self.opts.log_debug_level )
        except AttributeError:
            self.opts.log_debug_level = None
        try:
            self.opts.log_directory
            print("DEBUG: Setting logging directory to: %s"
                  %  (self.opts.log_directory))
            LDASLogging.setLogOutputDirectory( self.opts.log_directory )
        except AttributeError:
            self.log_directory = None

    def query( self ):
        #----------------------------------------------------------------
        # This method uses the actual TCL interpreter so there is
        #   no confusion of proper translation of string.
        #---------------------------------------------------------------- 
        resampling = 0
        l = int(tcl_interp("set query %s; llength $query" % self.opts.query_tcl))

        result = []
        for counter in range( l ):
            sq = tcl_interp( "lindex $query %d" % counter )
            print ('DEBUG: sq: %s' % sq)
            sql = int(tcl_interp("set squery {%s}; llength $squery" % sq ))
            print ('DEBUG: sql: %s' % sql)
            sqa = []
            for csq in range ( sql ):
                sqa.append( tcl_interp( "lindex $squery %d" % csq ))
            self.queries.append( sqa )
            print("DEBUG: sqa: %s" % sqa)

        #----------------------------------------------------------------
        # Construct the diskcache server request
        #----------------------------------------------------------------
        diskcache_args = []
        for q in self.queries:
            print("DEBUG: q: %s" % q)
            ifo = q[ self.OFFSET_IFO ]
            desc = q[ self.OFFSET_DESC ]
            print("DEBUG: ifo: %s desc: %s" % ( ifo, desc ) )
            t = q[ self.OFFSET_TIME_RANGE ].split( '-' );
            self.opts.outputTimeStart = int( t[0] )
            self.opts.outputTimeEnd = int( t[1] )
            #--------------------------------------------------------
            # Parse out the list of channels
            #--------------------------------------------------------
            chan = q[ self.OFFSET_CHANNELS ]
            cb = string.find( chan, '(' )
            cb = cb + 1
            ce = string.rfind( chan, ')' )
            c = chan[cb:ce]
            channels = string.split( c, ',' )
            resamples = []
            x = 0
            for channel in channels:
                tmp = string.split(channel, '!')
                l = len(tmp)
                if l == 1:
                    r = 1
                elif l == 2:
                    r = int( tmp[1] )
                channels[x] = tmp[0]
                resamples.append( r )
                if r > 1:
                    resampling = 1
                print ( "Channel: %s Resampling: %d" % ( channels[x], r ) )
                x = x + 1
            results = []
            try:
                print( "DEBUG: q[a]: %s" % ( q[ self.OFFSET_IFO ] ) )
                print( "DEBUG: q[b]: %s" % ( q[ self.OFFSET_DESC ] ) )
                print( "DEBUG: opts.outputTimeStart: %s"
                       % ( self.opts.outputTimeStart ) )
                results = self.server.FilenamesRDS( q[ self.OFFSET_IFO ],
                                                    q[ self.OFFSET_DESC ],
                                                    self.opts.outputTimeStart,
                                                    self.opts.outputTimeEnd,
                                                    resampling,
                                                    '.gwf' );
                print results
            except Exception,e:
                print( "WARNING: exception: %s" % ( e ) )
            else:
                #--------------------------------------------------------
                # Have a collection of filenames
                #--------------------------------------------------------
                print results
                print( "DEBUG: directory_output_frames: %s" % self.opts.directory_output_frames )
                print( "DEBUG: directory_output_md5sum: %s" % self.opts.directory_output_md5sum )

                LDASframe.createRDSSet( results,
                                        channels,
                                        self.opts )
                print( "DEBUG: Done" )
                              

def main():
    # (self.opts, args) = parser.parse_args( )

    # server.Server( self.opts.host, int(self.opts.port) )
    crds = createRDS( )
    crds.query( )

if __name__ == '__main__':
    main()
