import base64
import threading
import time
from pathlib import Path

import cv2
import numpy as np
from tqdm import tqdm

import zmq

if __name__ == '__main__':
    # r1 = base64.b64encode(Path('/home/lambda/Pictures/drawing.png').read_bytes()).decode()
    # r1 = base64.b64encode(Path('/home/lambda/Pictures/remilia3.png').read_bytes()).decode()
    # requests.post('http://localhost:12345/sendpic/test', json=dict(value='data:image/png;base64, ' + r1))

    # for p in tqdm(Path('/home/lambda/Videos/pngs/New Folder/').glob('*.png')):
    #     r1 = base64.b64encode(p.read_bytes()).decode()
    #     requests.post('http://localhost:12345/sendpic/test', json=dict(value='data:image/png;base64, ' + r1))

    # arr = [cv2.imread(str(img)).tobytes() for img in Path('/home/lambda/Videos/pngs/New Folder/').glob('*.png')]
    arr = []
    for img in tqdm(list(Path('/home/lambda/Videos/pngs/New Folder/').glob('*.png'))):
        img = cv2.imread(str(img))
        # img = cv2.resize(img, (1920 // 2, 1080 // 2))

        img = img.reshape(1080, 1920, 3)
        z = np.zeros((1080, 1920, 4), dtype=np.uint8)
        z[:, :, :3] = img
        img = z
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)

        arr.append(img.tobytes())

    # img = cv2.resize(img, (1920 // 4, 1080 // 4,))

    # while True:
    #     for p in Path('/home/lambda/Videos/pngs/New Folder/').glob('*.png'):
    #         img = cv2.imread(str(p))
    #         # print(img.shape)
    #         input()
    #         socket.send(img.tobytes())
    # while True:
    #     for b in arr:
    #         input()
    #         socket.send(b)
    lii = [0, True]


    def t(li):
        context = zmq.Context()
        socket = context.socket(zmq.PUSH)
        socket.connect("tcp://localhost:5555")
        while True:
            for i, b in enumerate(arr):
                while True:
                    socket.send(arr[li[0]])
                    time.sleep(1 / 120)
                    if li[1]:
                        li[0] = i
                        break




    threading.Thread(target=t, args=(lii,)).start()

    # while True:
    #     for i, b in enumerate(arr):
    #         # input()
    #         lii[0] = i
    #         time.sleep(1 / 60)
    while True:
        input()
        lii[1] = not lii[1]
