import zmq
import cv2
import numpy as np
import struct
import time

context = zmq.Context()
context2 = zmq.Context()

#  Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://192.168.0.12:5555")
socket2 = context2.socket(zmq.REQ)
socket2.connect("tcp://192.168.0.12:5556")

recordFrames = 0
startTime = 0

def draw_circle(event, x, y, flags, param):
    global recordFrames
    if event == cv2.EVENT_LBUTTONDOWN:
        print(img[y][x]>>8, img[y][x]&0xff)
        print(b[y][x]>>8, b[y][x]&0xff)
        recordFrames = 300
        startTime = time.time()
        
        

with open("lepton_log.bin", "wb") as f:
    pass
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_circle)
while 1:
    socket.send(b"Hello")

    #  Get the reply.
    message = socket.recv()
    socket2.send(b"Hello")
    gridEyeData = socket2.recv()
    if recordFrames > 0:
        print ("left frames", recordFrames)
        with open("lepton_log.bin", "ab") as f:
            f.write(message)
            f.write(gridEyeData)
        recordFrames -= 1
        sleepTime = 0.1 - (time.time() - startTime)
        if sleepTime > 0:
            time.sleep(sleepTime) # wait 0.1 second
        startTime = time.time()
        continue
    img = np.array(struct.unpack("<19200H", message), dtype=np.uint16).reshape((120, 160))
    # img = np.ndarray(shape=(19200,),dtype='<u2', buffer=message).reshape((120, 160))
    #img = np.frombuffer(message, dtype=np.uint16).reshape((120, 160))
    b = img.copy()
    for x in range(160):
        for y in range(120):
            b[y][x] = ((img[y][x]&0xff)<<8) + (img[y][x]>>8)
    b = cv2.normalize(b, dst=None, alpha=0, beta=65535, norm_type=cv2.NORM_MINMAX)
    #img = img.astype(np.uint8)
    #image = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    #cvuint8 = cv2.convertScaleAbs(image)
    cv2.imshow("image", b)
    # cv2.imshow("image_o", img)
    gridEyeImg = np.frombuffer(gridEyeData, dtype=np.uint8).reshape((32, 8))
    cv2.imshow("gridEyeImg", cv2.resize(gridEyeImg, (160, 640)))
    key = cv2.waitKey(100)
    if key == ord('q'):
        break

cv2.destroyAllWindows()