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

"""
 About this program
**********************************************************************
 Вывод статистических отчётов по результатам моделирования
 - Единица времени равняется 10msc (милисекунд)
 - Размер страницы измеряется в байтах
**********************************************************************

"""

__version__ = '$ Revision: 0.2.2 $ Date: 2003/05/29 17:22: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

#--[ Special variables ]----------------------------------------
try:
    SimConfigName = sys.argv[1]
except IndexError:
    SimConfigName = 'SimConfig.ini'
    
cfg = ConfigParser()
cfg.read(getcwd()+'\\'+SimConfigName)

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

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

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, pre, varname, myr, iter, traceout=0):
        self.conn = conn
        self.var = varname
        self.k = 0
        if myr == "0":
            self.tname = pre+varname+`iter`
            self.fname = pre+"_"+varname+`iter`
        else:
            self.tname = pre+varname+str(myr)+"_"+`iter`
            self.fname = pre+"_"+varname+str(myr)+"_"+`iter`


    def work(self):
#        self.ofile.write("Report of %s for %s\n"%(self.var, self.tname))
        vd = cfg.get('reportOptions','ReportValuesDelimiter')
        curs = self.conn.cursor()
        try:
            curs.execute("select * from %s order by sid"%self.tname)
            ofile = file(cfg.get('reportOptions','ReportDirectory')+
                         self.fname+
                         cfg.get('reportOptions','ReportFileExtension'),"w+")

            re = curs.fetchone()
            while re:
                s = "%s%s%4.1f\n"%(re[1],vd,re[2])
                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("\n")
    putfile("-=[ Simulation Log, started %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    putfile("---[ SimReport "+__version__+" ]--")
    putfile("-< Used %s configuration file"%SimConfigName)

    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','RobReportStatVars'),","):
            rep = Report(dbconn, "rob", key, "0", jj)
            rep.work()
            k+=rep.getk()

        for key in split(cfg.get('reportOptions','RobsReportStatVars'),","):
            for r in range(cfg.getint('robotOptions','RobotQuantity')):
                rr = r + 1
                rep = Report(dbconn, "rob", key, rr, jj)
                rep.work()
                k+=rep.getk()

        for key in split(cfg.get('reportOptions','SenReportStatVars'),","):
            rep = Report(dbconn, "sen", key, "0", 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("---[ SimReport "+__version__+" ]--")
    putfile("-=[ Simulation Log, finished %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    flog.close()
    dbconn.close()

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