import zmq,json,time,random

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://127.0.0.1:7777')
sub.setsockopt(zmq.SUBSCRIBE,'')
pub = ctx.socket(zmq.PUB)
pub.connect('tcp://127.0.0.1:6666')

def paint(payload,oldpos):
        newpayload = {
            'id' : id(oldpos),
            'event' : 'drawLine',
            'x': oldpos['x'],
            'y': oldpos['y'],
            'x2': payload['x'],
            'y2': payload['y'],
            'stroke': 'blue',
            'lineWidth' : 10
        }
        pub.send_multipart(('*',json.dumps(newpayload)))
        print('send',newpayload)
        return newpayload

def oklen(payload,oldpos):
    return abs(payload['x'] - oldpos['x']) > 30 or abs(payload['y']-oldpos['y']) > 30
        
expire = 100000
oldpos = None
lst = []

class brushhss(object):
    def __init__(self,uuid):
        self.uuid = uuid
        self.oldpos = None
        self.color = '%06x' % random.randrange(16**6)
        self.timestamp = int(round(time.time() * 1000))

    def apply(self,payload):
        if 'event' in payload:
            event = payload['event'] 
            if event == 'mouseup':
                pass
                #throw out oldpos
            elif event == 'mousedown':
                pass
                #makesure oldpos is updated
            elif event == 'mousedrag':
                pass
                #here we emit
    def mouseup(self,event):
        pass

    def mousedown(self,event):
        pass

    def mousedrag(self,event):
        pass

brushlst = {}

while True:
    now = int(round(time.time() * 1000))
    nlst = []
    for _id,emited in lst:
        if emited + expire < now:
            print('trash',_id)
            pub.send_multipart(('*',json.dumps({'id':_id,'trash':1})))
        else:
            nlst.append((_id,emited))
    lst = nlst
    uuid,data = sub.recv_multipart()
    try:
        data = json.loads(data)
        #assign color
        if not uuid in brushlst:
            brushlst[uuid] = brushhss(uuid)
        brushlst[uuid].apply(data)
        if 'event' in data:
            if data['event'] == 'mousedrag':
                if oldpos:
                    tmp = paint(data,oldpos)
                    lst.append((tmp['id'],now))
            if data['event'] in ['mouseup','mousedrag']:
                
                if not oldpos or oklen(data,oldpos):
                    oldpos = data
            if data['event'] == 'mouseup':
                oldpos = None
        #pub.send_multipart(('*',json.dumps(payload)))
    except Exception as e:
        print('shit')
        print(data)
        print(e)
        pass
    #ckeck time with timestamp for each id
    #if delta more than threshold, emit trash for this id
pub.close()
sub.close()
ctx.term()
