import threading
import Queue
import time
import whatap.agent.conf.configure as config
import whatap.agent.secure.security_master as secure
import whatap.pack.text_pack as text_pack
from whatap.util.date_util import DateUtil as dateutil
import whatap.util.hash_util as hash
import whatap.net.sender as sender
import whatap.net as net
from datetime import datetime

hash_cache = {}

class __DataText (threading.Thread):
    def __init__(self) :
        threading.Thread.__init__(self, name='__DataText')
        self.setDaemon(True)
        self.__queue = Queue.Queue()
        self.__hour = 0

    def queue(self, sendinfo):
        self.__queue.put(sendinfo)

    def run(self):
        
        while True:
            
            self.__run()
            self.__clearCache()
            time.sleep(10)

    def __clearCache(self):
        global hash_cache
        if datetime.now().hour != self.__hour:
            self.__hour = datetime.now().hour
            hash_cache.clear()

    def __run(self):
        rec = []
        try:
            while True:
                rec.append( self.__queue.get_nowait() )
        except Queue.Empty, e:
            pass

        if not rec:
            return
        sm= secure.GetSecurityMaster()
        p= text_pack.TextPack()
        p.pcode = sm.pcode
        p.oid = sm.oid
        p.time = dateutil.now()
        p.addTexts(rec)

        sender.Send(net.NET_SECURE_CYPHER, p)

dataText = __DataText()
dataText.start()

class TextKey :
    def __init__(self, div, hash):
        self.__div = div
        self.__hash = hash

    def Hash(self):
        return int(self.__.hash ^ int(self.__div<<32))

    def Equals(self, o):
        return self.__div == o.div and self.hash == o.hash

def sendText(div , text ):
    h = hash.HashStr(text)
    #dataText.queue( text_pack.TextRec(div= div, hash= h, text= text) )
    sendHashText(div, h, text)


def sendHashText(div , h , text ):
    global hash_cache
    if h not in hash_cache:
        dataText.queue(text_pack.TextRec(div=div, hash=h, text=text))
        hash_cache[h] = None


