#!/usr/bin/python
from redis.sentinel import Sentinel
#import connect
import moduleIO
import monitorIO
from multiprocessing import Process, Manager
#from redis.sentinel import Sentinel
import dataReduction
import os
import glob
import getCommand
import heartBeat
import subprocess
import shlex


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)
    print pid, mypid
    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',
                filemode='w')

        self.logger = logging.getLogger('GPPD')
        #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())
    # ======Try to connect NEON server
    ip_port = [('10.1.33.141', 9001)]
    passwd = 'sanlie;123'
    sentinel = Sentinel(ip_port, socket_timeout=10)
    r=sentinel.master_for('neonmaster', socket_timeout=30, password=passwd)



    #r = connect.connectNeon(ip_port, passwd, 10)
    #r = r.getRedisWrite()
    #r_read = r.getRedisRead()

    for file in glob.glob('./*.nxs'):
        os.remove(file)
    print "clear all nxs file"
    #moduleList=['module131']
    moduleList=['module131', 'module132', 'module133', 'module231', 'module232', 'module233', 'module322', 'module331', 'module332', 'module333', 'module341', 'module342', 'module343', 'module422', 'module431', 'module432', 'module433', 'module441', 'module442', 'module443', 'module521', 'module522', 'module523', 'module531', 'module532', 'module533', 'module541', 'module542', 'module543', 'module621', 'module622', 'module623', 'module631', 'module632', 'module633', 'module641', 'module642', 'module643']
    #moduleList=['module422']
    #moduleList=['module621', 'module622']
    monitorList=['monitor1','monitor2','monitor3']

    #set command
    manager = Manager()
    myDict=manager.dict()
    myDict['configure'] = False
    myDict['running']= False
    myDict['error']=False
    print 'waiting . . .'
    init=1
    r.set("/GPPD/stateMachine/status",init)

    # create and start command thread and heartbeat thread
    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=[]
    for name in moduleList:
        myPro.append(moduleIO.moduleIO(r, 1, name, myDict,logger))
    myPro.append(monitorIO.monitorIO(r, 1,monitorList, myDict,logger))
    myPro.append(dataReduction.reduction(r, 30, myDict,logger))
    for t in myPro:
        t.start()
        print t," start!"
