import sys
import time

import cv2
import numpy as np
from PyQt6.QtCore import QByteArray, Qt
from PyQt6.QtGui import QImage, QPixmap, QKeyEvent, QWheelEvent
from PyQt6.QtWidgets import QMainWindow, QApplication, QGraphicsPixmapItem, QGraphicsScene

from flandre.config import C
from flandre.nodes.Node import Node
from flandre.pyqt.Image import Ui_MainWindow
from flandre.pyqt.ZMQReceiver import ZMQReceiver
from flandre.utils.Msg import KillMsg, Msg, BMMsg, RfMatMsg, KeyPressMsg, RGB888Msg
from flandre.utils.RfMat import RfMat


class Adv(QMainWindow, Ui_MainWindow):
    def __init__(self, p: Node, parent=None):
        super(Adv, self).__init__(parent)
        self.p = p
        self.setupUi(self)
        zmq_receiver = ZMQReceiver(self)
        zmq_receiver.zmq_event.connect(self.on_zmq_event)
        zmq_receiver.start()
        self.g = QGraphicsPixmapItem()
        self.s = QGraphicsScene()
        self.s.addItem(self.g)
        self.graphicsView.setScene(self.s)
        self.grey = False
        self.scale = False
        self.watermark = True
        self.zoom = 1.0
        self.need_fit = False

    def keyPressEvent(self, a0: QKeyEvent):
        t = a0.text()
        match t:
            case 'm':
                self.grey = not self.grey
            case 's':
                self.scale = not self.scale
                if not self.scale:
                    self.need_fit = True
            case 't':
                self.watermark = not self.watermark

    def wheelEvent(self, a0: QWheelEvent):
        if a0.angleDelta().y() > 0:
            self.zoom += 0.1
        if a0.angleDelta().y() < 0:
            self.zoom -= 0.1

    def on_zmq_event(self, msg: QByteArray):
        msg = Msg.decode_msg(msg.data())
        if isinstance(msg, KillMsg):
            if msg.name == '':
                self.close()
        elif isinstance(msg, RfMatMsg):
            w = msg.rfmat.w
            h = msg.rfmat.h
            d: RfMat = msg.rfmat
            d2 = (d
                  .resize((int(w * self.zoom), int(h * self.zoom)))
                  .watermark(cond=self.watermark)
                  )
            w = d2.w
            h = d2.h
            qImg = QImage(
                d2.__bytes__(),
                w, h, 1 * w,
                QImage.Format.Format_Grayscale8
            )
            self.g.setPixmap(QPixmap(qImg))
            self.s.setSceneRect(0.0, 0.0, w, h)
            if self.scale:
                self.graphicsView.fitInView(self.s.sceneRect())
            else:
                if self.need_fit:
                    self.graphicsView.fitInView(self.s.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio)
                    self.need_fit = False
        # elif isinstance(msg, RGB888Msg):
        #     w = msg.w
        #     h = msg.h
        #             d: RfMat = msg.rfmat
        #             d2 = (d
        #                   .resize((int(w * self.zoom), int(h * self.zoom)))
        #                   .watermark(cond=self.watermark)
        #                   )
        #             w = d2.w
        #             h = d2.h
        #             if self.grey:
        #                 qImg = QImage(
        #                     d2.__bytes__(),
        #                     w, h, w,
        #                     QImage.Format.Format_Grayscale8
        #                 )
        #             else:
        #                 qImg = QImage(
        #                     d2.__bytes__(),
        #                     w, h, 3 * w,
        #                     QImage.Format.Format_BGR888
        #                 )
        #             self.g.setPixmap(QPixmap(qImg))
        #             self.s.setSceneRect(0.0, 0.0, w, h)
        #             if self.scale:
        #                 self.graphicsView.fitInView(self.s.sceneRect())
        #             else:
        #                 if self.need_fit:
        #                     self.graphicsView.fitInView(self.s.sceneRect(), Qt.AspectRatioMode.KeepAspectRatio)
        #                     self.need_fit = False
        #
        #             RGB888Msg


class ImageQt(Node):
    topics = [BMMsg, RfMatMsg, KeyPressMsg]

    def __init__(self):
        super().__init__()

    def loop(self):
        app = QApplication(sys.argv)
        MainWindow = Adv(self)
        # MainWindow.move(int(px), int(py))
        # MainWindow.resize(int(sx), int(sy))
        MainWindow.show()
        app.exec()
