#! /usr/local/bin/python
### SimMergeReports.py, by Ilya A. Zemskov(zemskov@univer.omsk.su)

"""
 About this program
**********************************************************************
Harvest report files into one file
**********************************************************************

"""

__version__ = '$ Revision: 0.2.0 $ Date: 2003/05/31 22:45:00 $'

from __future__ import generators
from time import localtime, strftime
import MySQLdb
from ConfigParser import *
from os import getcwd
import sys
from string import split
#---------------------------------------------------------------
comini = "..\\ini\\common.ini"
dbini = "..\\ini\\db.ini"

#--[ Special variables ]----------------------------------------
try:
    taskdir = sys.argv[1]
except IndexError, msg:
    sys.exit("Error: missing parameter - name of task directory")

try:
    taskinifile = sys.argv[2]
except IndexError, msg:
    sys.exit("Error: missing parameter - name of ini file")

#application common
comcfg = ConfigParser()
comcfg.read(comini)
wdir = comcfg.get('Options','WorkDirectory')

#db common
dbcfg = ConfigParser()
dbcfg.read(dbini)

#task private
cfg = ConfigParser()
cfg.read(wdir+taskdir+'\\ini\\'+taskinifile)

flog = file(cfg.get('logOptions','LogDirectory')+
            cfg.get('logOptions','LogFileName'),
            "a+")

dbconn = MySQLdb.Connect(dbcfg.get('dbOptions','Host'),
                         dbcfg.get('dbOptions','Login'),
                         dbcfg.get('dbOptions','Password'))

TRACETOFILE = cfg.getint('logOptions','LogTraceToFile')

#---------------------------------------------------------------
def putfile(st):
    if TRACETOFILE:
        flog.write(st+"\n")
        flog.flush()
    else:
        print st

#--[ Report classes ]----------------------------------------
class Report:
    """ 
    """
    def __init__(self, conn, varname, iter, traceout=0):
        self.conn = conn
        self.var = varname
        self.tname = varname+`iter`
        self.fname = varname+`iter`
        self.tf = ""
        self.tabl = ""
        self.ft1 = "%s.%s"%(cfg.get('dbOptions','DBName1'), self.tname)
        for i in range(1, cfg.getint('reportOptions','ReportsCount')):
            ii = i+1
            ttabl = "%s.%s"%(cfg.get('dbOptions', 'DBName'+str(ii)), self.tname)
            self.tf += ", %s.varval"%(ttabl)
            self.tabl += "LEFT JOIN %s ON %s.stime=%s.stime "%(ttabl, self.ft1, ttabl)
        self.k = 0

    def work(self):
        vd = cfg.get('outOptions','outValuesDelimiter')
        curs = self.conn.cursor()
        sql ="""
            SELECT %s.stime, %s.varval%s
            FROM %s %s           
            """%(
                self.ft1,
                self.ft1,
                self.tf,
                self.ft1,
                self.tabl)
        try:
            curs.execute(sql)
            ofile = file(cfg.get('outOptions','outDirectory')+
                              self.fname+
                              cfg.get('outOptions','outFileExtension'),"w+")

            re = curs.fetchone()
            while re:
                s = "%s"%re[0]

                for j in range(1, cfg.getint('reportOptions','ReportsCount')+1):
                    s = s + "%s%4.1f"%(vd,re[j])

                s += "\n"

                ofile.write(s.replace(".",","))
                ofile.flush()
                re = curs.fetchone()

            ofile.close()
            self.k = 1
        except MySQLdb.Error,msg:
            putfile("--< MySQL error: %s "%msg)

        curs.close()

    def getk(self):
        return self.k
    
#-----------------------------------------------------------------
  
def main():
    global dbconn
    putfile("-=[ Simulation Log, started %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    putfile("---[ SimMergeReports "+__version__+" ]--")
    putfile("-< Used %s configuration file"%(wdir+taskdir+'\\ini\\'+taskinifile))

    k=0
    for j in range(cfg.getint('simOptions','Iterations')):
        jj = j+1
        putfile("----[ Run: "+`jj`+" ]------------------------------------------------")
        putfile("-< Run out reports")

        for key in split(cfg.get('reportOptions','ReportStatVars'),","):
	    
            rep = Report(dbconn, key, jj)
            rep.work()
            k+=rep.getk()
       
        putfile("-< End out reports")
        putfile("----[ Run: "+`jj`+" ]------------------------------------------------")
        print "\n"        
    putfile("----[ Statistics ]-------------------------------------------")
    putfile("--< Created %d report's files"%k)
    putfile("----[ Statistics ]-------------------------------------------")
    putfile("---[ SimMergeReports "+__version__+" ]--")
    putfile("-=[ Simulation Log, finished %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    flog.close()
    dbconn.close()

#--[ Main program :) ]------------------------------------------
if __name__ == '__main__':
    main()
