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

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

"""

__version__ = '$ Revision: 0.1.0 $ Date: 2003/05/7 11:40: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')

pages = cfg.getint('pageOptions','PageCount')

robots = cfg.getint('robotOptions','RobotQuantity')

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

def addpage(conn, pid, rob):
    curs = conn.cursor()
    curs.execute("insert into %s values('%d','%d')"%
                 (cfg.get('dbOptions','RobRouteTableName'),
                  pid,
                  rob))
    curs.close()

#-----------------------------------------------------------------
  
def main():
    global dbconn, pages, robots
    putfile("\n")
    putfile("-=[ Simulation Log, started %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    putfile("---[ SimRobRoute "+__version__+" ]--")
    putfile("-< Used %s configuration file"%SimConfigName)

    curs = dbconn.cursor()
# Create RobRoute table
    try:
        curs.execute("drop table %s"%cfg.get('dbOptions','RobRouteTableName'))
    except MySQLdb.Error,msg:
        print "MySQL error:",msg
        pass
    curs.execute("create table %s(%s)"\
                 %(cfg.get('dbOptions','RobRouteTableName'),\
                   cfg.get('dbOptions','RobRouteTableFieldsSQL')))
    curs.close()

    delta = pages / robots

    k=1
    for j in range(cfg.getint('robotOptions','RobotQuantity')):
        jj = j+1
        putfile("----[ Robot: "+`jj`+" ]------------------------------------------------")
        putfile("-< Run create robot route")

        if pages - jj*delta <= delta:
        	limd = pages + 1
	else:
		limd = k + delta

        while k < limd:
		addpage(dbconn, k, jj)
		k += 1

        putfile("-< End create robot route")
        putfile("----[ Robot: "+`jj`+" ]------------------------------------------------")
        print "\n"        
    putfile("---[ SimRobRoute "+__version__+" ]--")
    putfile("-=[ Simulation Log, finished %s ]=-"%strftime("%d.%m.%Y %H:%M:%S", localtime()))
    flog.close()
    dbconn.close()

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