import whatap.util.thread_util as thread_util
tcpCheckRunning = False
import socket

def getCheckTCP(checkUrl ="", timeout =0):
    words = checkUrl.split(":")
    if len(words) < 3:
        raise Exception("tcp port check url error {}".format(checkUrl) )

    protocol = words[0]
    address = words[1].replace("/", "")

    try:
        port=int(words[2])
    except ValueError, e:
        raise Exception("tcp port check url error(int required) {}".format(checkUrl) )
        
    if port < 1:
        Exception("tcp port check url error(negative port) {}".format(checkUrl) )
    
    if protocol == "tcp":
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        try:
            s.connect((address, port))
            return (address, port, True)
        except socket.error:
            return (address, port, False)
        finally:
            s.close()

def tcpCheckSchedule(checkurls, timeout, onPerf):
    global tcpCheckRunning
    if tcpCheckRunning:
        return
    
    tcpCheckRunning = True

    def tcpCheckAll():
        global tcpCheckRunning
        perfs = []
        for checkurl in checkurls:
            try:
                perf = getCheckTCP(checkurl, timeout)
                perfs.append(perf)
            except:
                pass    
        if perfs:
            onPerf(perfs)
        tcpCheckRunning = False

    thread_util.async(tcpCheckAll)