# $CVSHeader: pal8e/src/Log.py,v 1.9 2005/02/15 01:10:26 indraneel Rel $

import os
import string
import time
from types import *
import gzip

class LogFH:
    def __init__(self, fname, mode='a', compress=0):
        if compress:
            fname = fname+'.gz'
        if os.path.isfile(fname):
            os.rename(fname, fname+'.bak')
        if compress:
            self.logfh = gzip.GzipFile(fname, mode, 1) #line buffered
        else:
            self.logfh = file(fname, mode, 1)
        message = 'LogFile opened in mode '+mode+' at '+str(time.ctime())+'\n'
        self.logfh.write(message)

    def log(self, message, handle=None):
        if type(message) == StringType:
            showtime = "% 7.2f" % (time.clock()) + ' '
            m = showtime
            if handle:
                m += handle + ' '
            message = [m + message+'\n']
        self.logfh.writelines(message)

    def close(self):
        message = "% 7.2f" % (time.clock())
        message += ' LogFile Closed at '+str(time.ctime())+'\n'
        self.logfh.write(message)
        self.logfh.close()
        del self.logfh

class PSSDLog(LogFH):
    def __init__(self, conf):
        self.structureID = conf.get('Input', 'structureID')
        dbgitems = conf.get('Debug', 'dbgitems')
        dbgitems = string.split(dbgitems)
        self.dbgitems = dbgitems
        if 'all' in self.dbgitems:
            self._log = 'All'
        elif 'none' in dbgitems:
            self._log = None
        else: self._log = 'Selected'
        if not self._log: return
        logfname = conf.get('Debug','dbgdir')+self.structureID
        compression = conf.getint('Output', 'compression')
        LogFH.__init__(self, logfname, 'w', compression)
        LogFH.log(self, 'Logging for '+self.structureID)

    def log(self, item, message, handle=None):
        if not self._log: return
        if (self._log == 'Selected') and \
           (item not in self.dbgitems): return
        LogFH.log(self, message, handle)

    def close(self):
        if 'none' in self.dbgitems:
            return
        LogFH.close(self)
