import logging
import multiprocessing
import time
from pathlib import Path

import cv2
import numpy as np
from tqdm import tqdm

from nodes.Beamformer import Beamformer
from nodes.Broker import Broker
from nodes.ImageCV import ImageCV
from nodes.Loader import Loader
from nodes.MainUI import MainUI
from nodes.Node import Node
from BusClient import BusClient
from utils.Msg import Msg1, Msg2, BMMsg, TickMsg, StrMsg, KillMsg
from nodes.WebRTC import WebRTC


class M1(Node):
    def loop(self):
        cnt = 0
        while True:
            cnt += 1
            self.send(str(cnt).encode())
            time.sleep(1)


class M2(Node):
    def loop(self):
        while True:
            print(self.recv())


class M3(Node):
    topics = [StrMsg]
    def loop(self):
        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())

        # while self.isalive:
        #     for b in arr:
        #         self.send(BMMsg(0, b))
        #         # self.pub_socket.send(b)
        #         # self.send(b)
        #         r = self.c.poller.poll(int(1000 / 60))
        #         # print(r)
        #         if r and Msg.decode_msg(r[0][0].recv()).name == '':
        #             self.isalive = False
        #             break
        #         # time.sleep(1 / 60)
        while self.isalive:
            for b in arr:
                msg = self.recv()
                if isinstance(msg, KillMsg):
                    if msg.name == '':
                        self.isalive = False
                        break
                self.send(BMMsg(0, b))

        # if r and Msg.decode_msg(r[0][0].recv()).name == '':


class M4(Node):
    def loop(self):
        while True:
            self.send(Msg1())
            time.sleep(1)


class MTIME(Node):
    def loop(self):
        while True:
            t = time.time()
            self.send(TickMsg(t))
            time.sleep(10)
            # print(t)


class MLISTEN(Node):
    topics = [StrMsg]

    def loop(self):
        while self.isalive:
            r = self.recv()
            print(r)
            if isinstance(r, KillMsg) and r.name == '':
                self.isalive = False
                break
            self.send(TickMsg(time.time()))


class M6(Node):
    topics = [Msg2.eid()]

    def loop(self):
        while True:
            print(self.recv())


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    multiprocessing.set_start_method('spawn')
    pps = []
    ps = [
        Broker(),
        WebRTC(),
        # M3(),
        MainUI(),
        ImageCV(),
        MLISTEN(),
        Beamformer(),
        Loader(),
    ]
    for p in ps:
        pps.append(multiprocessing.Process(target=p))
    for p in pps:
        p.start()

    c = BusClient(KillMsg)
    while True:
        x: KillMsg = c.recv()
        if x.name == '':
            break
    for p in pps:
        p.kill()
