#!/usr/bin/python
import moduleIO
import monitorIO
import getCommand
import heartBeat
import connect
from multiprocessing import Process, Manager
import subprocess
import shlex
import os

def run_this():
    mypid=str(os.getpid())
    myname=os.path.basename(__file__)
    _cmd="ps -C "+myname+" -o pid="
    pid=subprocess.check_output(_cmd, shell=True)
    pid=shlex.split(pid)
    for p in pid:
        if p != mypid:
            try:
                _cmd="/usr/bin/kill -9 "+str(p)
                #_cmd = shlex.split(_cmd)
                subprocess.check_call(_cmd, shell=True)
                print "process  killed", p
                #logger.warning("Self process killed")
            except:
                print "process not killed", p
                #logger.warning("Self process not killed")
        else:
            pass
    print mypid
    print pid
    return mypid

class myLog():
    def __init__(self):
        import logging
        from logging.handlers import RotatingFileHandler
        logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myMantid.log',
                #filename='myTest.log',
                filemode='w')

        self.logger = logging.getLogger('SANS')
        #hdlr = logging.FileHandler(os.getcwd()+'/RMmantid.log', maxBytes=100, backupCount=5)
        #hdlr = RotatingFileHandler(os.getcwd()+'/RMmantid.log', maxBytes=100, backupCount=5)
        #formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        #hdlr.setFormatter(formatter)
        #self.logger.addHandler(hdlr)
        #self.logger.setLevel(logging.DEBUG)

    def getLog(self):
        return self.logger


if __name__ == '__main__':
    _log=myLog()
    logger= _log.getLog()
    mypid=run_this()
    mypid=str(os.getpid())
    #ip_port = [('10.1.53.240', 9001), ('10.1.53.240',9001)]
    ip_port = [('10.1.34.116', 9001), ('10.1.34.116',9001)]
    passwd = 'sanlie;123'
    r = connect.connectNeon(ip_port, passwd, 10)
    r = r.getRedisWrite()

    moduleList=['module1', 'module2', 'module3', 'module4', 'module5', 'module6', 'module7', 'module8', 'module9', 'module10']
    #monitorList=['monitor1','monitor2','monitor3']
    manager = Manager()
    myDict=manager.dict()
    myDict['configure'] = False
    myDict['running']= False
    myDict['error']=False

    print 'waiting . . .'
    init=1
    r.set("/SANS/stateMachine/status",init)

    myCommandThread=getCommand.getCommand(r, 0.1, myDict, logger)
    myCommandThread.start()
    print myCommandThread, " start!"
    # heartbeat process
    myHeartbeatThread=heartBeat.neonHeartBeat(r, 0.5, mypid)
    myHeartbeatThread.start()
    print myHeartbeatThread," start!"

    myPro=[]
    myPro.append(moduleIO.moduleIO(r, 0.1, moduleList, myDict, logger))
    myPro.append(monitorIO.monitorIO(r, 10, myDict, logger))
    for t in myPro:
        t.start()
        print t," start!"
