# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'color_picker_dialog_box.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from .constants import *

class Ui_Dialog(object):
    def setupUi(self, Dialog, label, color_btn):
        self.mask = display_settings["list_of_mask"][-1]
        self.label_target = label 
        self.color_btn = color_btn
        self.Dialog = Dialog
        self.Dialog.setObjectName("Dialog")
        self.Dialog.resize(381, 216)
        self.buttonBox = QtWidgets.QDialogButtonBox(self.Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 170, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(self.Dialog)
        self.plainTextEdit.setGeometry(QtCore.QRect(10, 60, 361, 31))
        self.plainTextEdit.setObjectName("plainTextEdit")
        self.label = QtWidgets.QLabel(self.Dialog)
        self.label.setGeometry(QtCore.QRect(150, 30, 71, 16))
        self.label.setObjectName("label")
        self.changeColor = QtWidgets.QPushButton(self.Dialog)
        self.changeColor.setGeometry(QtCore.QRect(150, 120, 75, 23))
        self.changeColor.setObjectName("pushButton")
        self.changeColor.clicked.connect(self.openColorPicker)

        self.retranslateUi(self.Dialog)
        self.buttonBox.accepted.connect(self.confirm_label_and_exit) # type: ignore
        self.buttonBox.rejected.connect(self.Dialog.reject) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(self.Dialog)

    def confirm_label_and_exit(self):
        # Get the text from the QPlainTextEdit
        text = self.plainTextEdit.toPlainText()
        if len(text)>0:
            # Set the text to the QLabel
            self.label_target.setText(text)
        self.Dialog.accept()

    def hex_to_rgb(self,hex_color):
        # Remove the hash '#' if present
        hex_color = hex_color.lstrip('#')

        # Convert the hex string to an integer tuple
        rgb_tuple = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

        return rgb_tuple

    def get_previous_color(self, stylesheet:str):
        stylesheet = stylesheet.replace(" ","")
        stylesheet = stylesheet.split("background-color:rgb")[1]
        stylesheet = stylesheet.split(";")[0]
        colors = stylesheet[1:-1].split(",")
        colors = [int(c) for c in colors]
        # turn it into bgr, which is cv2 default
        colors = (colors[2],colors[1],colors[0])
        return colors

    def openColorPicker(self):
        # Open the color picker dialog
        color = QColorDialog.getColor()

        # Check if a valid color is selected
        if color.isValid():
            # Get the current stylesheet
            current_stylesheet = self.color_btn.styleSheet()
            
            # Remove any existing background-color entry
            if "background-color" in current_stylesheet:
                previous_color = self.get_previous_color(current_stylesheet)
                # Remove the existing background-color rule
                start_idx = current_stylesheet.index("background-color:")
                end_idx = current_stylesheet.index(";", start_idx)
                current_stylesheet = current_stylesheet[:start_idx] + current_stylesheet[end_idx + 1:].strip()

            # Add the new background color to the cleaned-up stylesheet
            # rgb is needed for the CSS stylesheet from the button colors
            new_rgb = self.hex_to_rgb(color.name())
            new_stylesheet = f"{current_stylesheet} background-color: rgb{new_rgb};"
            # bgr is needed to change the color of the brush to its new value 
            new_bgr = new_rgb[2],new_rgb[1],new_rgb[0]
            
            # set the new stylesheet for this button and update the pixels in the screen that matched the previous color
            self.color_btn.setStyleSheet(new_stylesheet)
            brush_settings["color"] = new_bgr
            
            # bgr_alpha is needed for the pixel values in the mask, as understood by cv2
            new_bgr_alpha = (*new_bgr,255)
            for mask in display_settings["list_of_mask"]:
                # replace the pixels with the previous color value for the new color in RGB format
                filtered_rgb_from_mask = mask[...,:3] #filter for all the values expect alpha channel
                mask_indices = (filtered_rgb_from_mask == previous_color).all(axis=-1)  # Find matching pixels
                mask[mask_indices] = new_bgr_alpha  # Update those pixels with the new color

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Label Name"))
        self.changeColor.setText(_translate("Dialog", "Color"))


if __name__ == "__main__":
    import sys
    # Enable High DPI scaling
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # Use the high-resolution icons and fonts
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
