import threading, time
import whatap.agent.conf.configure as config
from whatap.io.data_outputx import DataOutputX
from whatap.io.data_inputx import DataInputX
import whatap.agent.secure.security_master as secure
import whatap.util.logging_util as logging_util
import socket

class DownCheckMain(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self, name='DownCheckHello')
        self.setDaemon(True)

    HOST = '0.0.0.0'
    def run(self):
        conf= config.GetConfig()
        if not conf.DownCheckListenEnabled :
            return
        while True:
            secu = secure.GetSecurityMaster()
            if not secu:
                time.sleep(0.1)
                continue
            try:
                s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.bind((self.HOST, conf.PeerPort))
                s.listen(5)
                while True:
                    conn = None
                    try:
                        conn, addr = s.accept()
                        conn.settimeout(3)

                        out = DataOutputX()
                        out.writeLong(secu.pcode)
                        out.writeInt(secu.oid)
                        conn.sendall(out.toByteArray())

                        instream = DataInputX(conn)
                        instream.readLong()
                        instream.readInt()
                    except Exception, e:
                        logging_util.logStack(e)
                        time.sleep(0.01)
                    finally:
                        if conn:
                            conn.close()
            except Exception, e:
                logging_util.logStack(e)
                time.sleep(1)
            finally:
                if s:
                    s.close()
