#
# RowReaderProcess()
# author  Maurizio Nagni
# version 1.0 - 21 September 2005
#
# This is the main thread for the managements of the RawReader processing.
#
# Parameters:
# - scriptHost     The directory where the ROOT scritps are stored  (required)
# - pitHost        The monitored directory for "new" files          (required)
# - sourceHost     The directory where to the "new" files are moved (optional)
#

import os, sys, time, threading, traceback, popen2
from ConfigParser import *


#------------------ rowReaderThread Class -----------------------------------------------------
class RawReaderProcess(threading.Thread):
    def __init__(self, pitHost="", configFile="", fileName="", logger=""):
        threading.Thread.__init__(self)
        self.__pitHost      = pitHost
        self.__fileName     = fileName
	self.__logger       = logger
        #gROOT.SetBatch(True)
	
	
	self.__config		  = ConfigParser()
	self.__config.optionxform = unicode
	self.__config.read(configFile)

        try:
		self.__executables	= self.__config.get('RawReaderProcess', 'executables')
	except NoSectionError, detail:
		raise Exception('Section missing in configuration file: ', detail)
	except NoOptionError, detail:
		raise Exception('Wrong option in configuration file: ', detail)
        

    def run(self):
        # Infinite loop waiting for file upload comes to an end
        self.__logger.info('Ready to unpack file' +  self.__fileName)
        try:
        	if(self.__unpack()):
                    self.__logger.info('Unpacked correctly')
        except:
            #traceback.extract_stack()
            self.__logger.exception('Error')
            #sys.stdout.flush()    
        sys.exit(0);



    # 
    # the scope of this function is to start a rawreader session
    #
    def __unpack(self):
        try:
                print 'rawreader ' + self.__pitHost  + '/   ' +self.__fileName
                terminal = os.popen(self.__executables + ' ' + self.__pitHost  + '/   ' +self.__fileName)  #<---- HERE START RawReader -
		self.__logger.info(string.join(terminal.readlines()))
		status = None
		try:
			# The close seems to generate an error. I catch in a except but nominally
			# it should "close" without problem. That's why in the except there is some fake code.
			# TO BE FIXED.
			status = terminal.close()
		except IOError:
			a = 0
			#self.__logger.error(' - ')
        	if (status == None):
			if (self.__benchmarkOn):
            			self.__bench.end()
			self.__logger.info('RawReader stopped correctly')

        except:
	    self.__logger.exception('Error')
            #traceback.print_exc(file=sys.stderr)
            #sys.stdout.flush()    
	    return False
	return True
