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

# Form implementation generated from reading ui file 'ui_V4.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 os.path import join as jn
import os
from .constants import *
from .edit_label_box import Ui_Dialog
from .warning_dialog_delete import Ui_Dialog as Ui_Dialog_Delete

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("LivePyxel")
        MainWindow.resize(1536, 672)
        MainWindow.setMinimumSize(QtCore.QSize(1536, 672))
        MainWindow.setStyleSheet("background-color: rgb(30, 30, 30);\n"
"color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        # Webcam feed
        self.script_path = os.path.dirname(os.path.abspath(__file__))
        print(self.script_path)
        [print(x) for x in os.listdir(self.script_path)]
        self.imageDisplay = WebcamWidget(self.centralwidget)
        self.imageDisplay.setMinimumSize(QtCore.QSize(720, 480))
        self.imageDisplay.setMaximumSize(QtCore.QSize(720, 480))
        self.imageDisplay.setStyleSheet("background-color: rgb(125,125,125);")
        self.imageDisplay.setText("")
        self.imageDisplay.setObjectName("imageDisplay")
        self.gridLayout_2.addWidget(self.imageDisplay, 2, 2, 1, 1)
        # Scrolling area
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setMaximumSize(QtCore.QSize(300, 600))
        self.scrollArea.setStyleSheet("background-color: rgb(60, 60, 60);\n""color: rgb(255, 255, 255);\n""")
        self.scrollArea.setFrameShadow(QtWidgets.QFrame.Raised)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents_3 = QtWidgets.QWidget()
        self.scrollAreaWidgetContents_3.setGeometry(QtCore.QRect(0, 0, 298, 478))
        self.scrollAreaWidgetContents_3.setObjectName("scrollAreaWidgetContents_3")
        self.gridLayout_6 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_3)
        self.gridLayout_6.setVerticalSpacing(20)
        self.gridLayout_6.setObjectName("gridLayout_6")
        # Create a new button
        self.label_block_0 = QtWidgets.QWidget(self.scrollAreaWidgetContents_3) #place a new widget as child of the scroll area
        # define new button block's policy and attributes
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_block_0.sizePolicy().hasHeightForWidth())
        self.label_block_0.setSizePolicy(sizePolicy)
        self.label_block_0.setMaximumSize(QtCore.QSize(16777215, 40))
        self.label_block_0.setObjectName("label_block_0")
        # button block has a layout as well
        self.horizontalLayout_13 = QtWidgets.QHBoxLayout(self.label_block_0)
        self.horizontalLayout_13.setObjectName("horizontalLayout_13")
        # add a label to the button block's layout
        self.label_select_0 = QtWidgets.QLabel(self.label_block_0)
        self.label_select_0.setObjectName("label_select_0")
        self.horizontalLayout_13.addWidget(self.label_select_0)
        # add a select button to the button block's layout
        self.btn_select_0 = QtWidgets.QPushButton(self.label_block_0)
        self.btn_select_0.setMaximumSize(QtCore.QSize(60, 16777215))
        self.btn_select_0.setStyleSheet("background-color: rgb(0, 255, 0);")
        self.btn_select_0.setText("")
        self.btn_select_0.setObjectName("btn_select_0")
        self.horizontalLayout_13.addWidget(self.btn_select_0)
        self.btn_select_0.clicked.connect(lambda: self.traverse_select_buttons(self.btn_select_0))
        # add an edit button to the button block's layout
        self.btn_edit_0 = QtWidgets.QPushButton(self.label_block_0)
        self.btn_edit_0.setMinimumSize(QtCore.QSize(20, 0))
        self.btn_edit_0.setMaximumSize(QtCore.QSize(30, 16777215))
        self.btn_edit_0.setText("")
        self.icon_edit = QtGui.QIcon()
        self.icon_edit.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/edit_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_edit_0.setIcon(self.icon_edit)
        self.btn_edit_0.setObjectName("btn_edit_0")
        self.horizontalLayout_13.addWidget(self.btn_edit_0)
        self.btn_edit_0.clicked.connect(lambda: self.traverse_edit_buttons(self.btn_edit_0))
        # add a remove button to the button block's layout
        self.btn_remove_0 = QtWidgets.QPushButton(self.label_block_0)
        self.btn_remove_0.setMinimumSize(QtCore.QSize(20, 0))
        self.btn_remove_0.setMaximumSize(QtCore.QSize(30, 16777215))
        self.btn_remove_0.setText("")
        self.icon_trash = QtGui.QIcon()
        self.icon_trash.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/trash_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_remove_0.setIcon(self.icon_trash)
        self.btn_remove_0.setObjectName("btn_remove_0")
        self.horizontalLayout_13.addWidget(self.btn_remove_0)
        self.btn_remove_0.setDisabled(True)
        self.btn_remove_0.setStyleSheet("background-color:rgb(45,45,45)")
        # self.btn_remove_0.clicked.connect(lambda: self.traverse_remove_buttons(self.btn_remove_0))
        
        
        
        self.gridLayout_6.addWidget(self.label_block_0, 1, 0, 1, 1)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents_3)
        self.gridLayout_2.addWidget(self.scrollArea, 2, 0, 1, 1)
        
        # Brush slider Settings — using manual geometry
        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.frame.setMinimumSize(QtCore.QSize(300, 80))  # same as scroll panel
        self.frame.setMaximumSize(QtCore.QSize(300, 80))  # lock width to match scroll area
        self.frame.setStyleSheet("background-color: transparent;")

        # First label and slider (e.g., Mask Opacity)
        self.label_6 = QtWidgets.QLabel(self.frame)
        self.label_6.setGeometry(QtCore.QRect(10, 0, 200, 16))  # wider label
        self.label_6.setText("Mask opacity")
        self.label_6.setObjectName("label_6")

        self.brush_slider = QtWidgets.QSlider(self.frame)
        self.brush_slider.setGeometry(QtCore.QRect(10, 20, 280, 20))
        self.brush_slider.setOrientation(QtCore.Qt.Horizontal)
        self.brush_slider.setObjectName("brush_slider")

        # Second label and slider (e.g., Binary Mask Threshold)
        self.label_7 = QtWidgets.QLabel(self.frame)
        self.label_7.setGeometry(QtCore.QRect(10, 40, 200, 16))
        self.label_7.setText("binary mask threshold")
        self.label_7.setObjectName("label_7")

        self.binarythres_slider = QtWidgets.QSlider(self.frame)
        self.binarythres_slider.setGeometry(QtCore.QRect(10, 60, 280, 20))
        self.binarythres_slider.setOrientation(QtCore.Qt.Horizontal)
        self.binarythres_slider.setObjectName("binarythres_slider")

        # Add to layout
        self.gridLayout_2.addWidget(self.frame, 0, 0, 1, 1)
        
        
        # Add section
        self.btn_add = QtWidgets.QPushButton(self.centralwidget)
        self.btn_add.setStyleSheet("background-color: rgb(80, 120, 80);")
        self.btn_add.setObjectName("btn_add")
        self.gridLayout_2.addWidget(self.btn_add, 3, 0, 1, 1)
        
        
        
        # Tip right panel with webcam related buttons
        self.widget_2 = QtWidgets.QWidget(self.centralwidget)
        self.widget_2.setMaximumSize(QtCore.QSize(800, 60))
        self.widget_2.setObjectName("widget_2")
        self.gridLayout = QtWidgets.QGridLayout(self.widget_2)
        self.gridLayout.setHorizontalSpacing(60)
        self.gridLayout.setObjectName("gridLayout")
        self.btn_annotate = QtWidgets.QPushButton(self.widget_2)
        self.btn_annotate.setMaximumSize(QtCore.QSize(120, 16777215))
        self.btn_annotate.setStyleSheet("background-color: rgb(60, 60, 80);")
        self.btn_annotate.setObjectName("btn_annotate")
        self.gridLayout.addWidget(self.btn_annotate, 0, 0, 1, 1)
        self.btn_capture = QtWidgets.QPushButton(self.widget_2)
        self.btn_capture.setMaximumSize(QtCore.QSize(120, 16777215))
        self.btn_capture.setStyleSheet("background-color: rgb(60, 70, 80);")
        self.btn_capture.setObjectName("btn_capture")
        self.gridLayout.addWidget(self.btn_capture, 0, 2, 1, 1)
        self.btn_switch_webcam = QtWidgets.QPushButton(self.widget_2)
        self.btn_switch_webcam.setMaximumSize(QtCore.QSize(120, 16777215))
        self.btn_switch_webcam.setStyleSheet("background-color: rgb(70, 60, 80);")
        self.btn_switch_webcam.setObjectName("btn_switch_webcam")
        self.gridLayout.addWidget(self.btn_switch_webcam, 0, 1, 1, 1)
        self.gridLayout_2.addWidget(self.widget_2, 0, 2, 1, 1)
        self.Label_Categories = QtWidgets.QLabel(self.centralwidget)
        self.Label_Categories.setMaximumSize(QtCore.QSize(16777215, 30))
        self.Label_Categories.setAlignment(QtCore.Qt.AlignCenter)
        self.Label_Categories.setObjectName("Label_Categories")
        self.gridLayout_2.addWidget(self.Label_Categories, 1, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1536, 22))
        self.menubar.setObjectName("menubar")
        self.menuFIle = QtWidgets.QMenu(self.menubar)
        self.menuFIle.setObjectName("menuFIle")
        self.menuTutorials = QtWidgets.QMenu(self.menubar)
        self.menuTutorials.setObjectName("menuTutorials")
        self.menuContact = QtWidgets.QMenu(self.menubar)
        self.menuContact.setObjectName("menuContact")
        # Add the action to the menu
        # Create an action within the menu
        self.contact_action = QtWidgets.QAction("Author's Website", self.menubar)
        self.menuContact.addAction(self.contact_action)
        self.contact_action.triggered.connect(lambda: os.startfile("https://urielgarcilazo.com/index.html"))
        # Create an action within the menu
        self.tutorials_action = QtWidgets.QAction("Project Website", self.menubar)
        self.menuTutorials.addAction(self.tutorials_action)
        self.tutorials_action.triggered.connect(lambda: os.startfile("https://ugarcil.github.io/LivePyxel/"))
        
        # ##############################################
        # Create a container widget for the new buttons
        self.button_container = QtWidgets.QWidget(self.widget_2)
        self.button_container.setMaximumSize(QtCore.QSize(80, 16777215))  # Max width of 80
        self.button_container.setObjectName("button_container")

        # Create a vertical layout for the container
        self.vertical_layout = QtWidgets.QVBoxLayout(self.button_container)
        self.vertical_layout.setContentsMargins(0, 0, 0, 0)  # Remove margins if desired
        self.vertical_layout.setSpacing(2)  # Adjust spacing between elements

        # Create a horizontal layout for the buttons
        self.button_row = QtWidgets.QHBoxLayout()
        self.button_row.setContentsMargins(0, 0, 0, 0)
        self.button_row.setSpacing(2)

        # Create and add the first button
        self.prev_btn = QtWidgets.QPushButton(self.button_container)
        self.prev_btn.setMaximumSize(QtCore.QSize(40, 40))
        self.prev_btn.setObjectName("prev_btn")
        self.prev_btn.setText("")        
        icon_binmask = QtGui.QIcon()
        icon_binmask.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/prev_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.prev_btn.setIcon(icon_binmask)
        self.prev_btn.setIconSize(QtCore.QSize(20, 20))
        self.button_row.addWidget(self.prev_btn)

        # Create and add the second button
        self.next_btn = QtWidgets.QPushButton(self.button_container)
        self.next_btn.setMaximumSize(QtCore.QSize(40, 40))
        self.next_btn.setObjectName("next_btn")
        self.next_btn.setText("")        
        icon_binmask = QtGui.QIcon()
        icon_binmask.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/next_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.next_btn.setIcon(icon_binmask)
        self.next_btn.setIconSize(QtCore.QSize(20, 20))
        self.button_row.addWidget(self.next_btn)

        # Add the button row to the vertical layout
        self.vertical_layout.addLayout(self.button_row)

        # Create and add the number input field
        self.number_input = QtWidgets.QLineEdit(self.button_container)
        self.number_input.setMaximumSize(QtCore.QSize(80, 25))  # Width matches container
        self.number_input.setAlignment(QtCore.Qt.AlignCenter)
        self.number_input.setValidator(QtGui.QIntValidator())  # Only allow integers
        self.number_input.setObjectName("number_input")
        self.number_input.setPlaceholderText("0")  # Default placeholder text
        self.vertical_layout.addWidget(self.number_input)

        # Add the container widget to the main grid layout
        self.gridLayout.addWidget(self.button_container, 0, 3, 1, 1)
        
        # #####################################################
        self.btn_switch_webcam = QtWidgets.QPushButton(self.widget_2)
        self.btn_switch_webcam.setMaximumSize(QtCore.QSize(120, 16777215))
        self.btn_switch_webcam.setStyleSheet("background-color: rgb(70, 60, 80);")
        self.btn_switch_webcam.setObjectName("btn_switch_webcam")
        self.gridLayout.addWidget(self.btn_switch_webcam, 0, 1, 1, 1)
        self.gridLayout_2.addWidget(self.widget_2, 0, 2, 1, 1)

        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.actionNew.triggered.connect(self.new_file_dialog)
        self.actionLoad_Folder_Ctrl_L = QtWidgets.QAction(MainWindow)
        self.actionLoad_Folder_Ctrl_L.setObjectName("actionLoad_Folder_Ctrl_L")
        self.actionLoad_Folder_Ctrl_L.triggered.connect(self.load_file_dialog)
        self.actionSaveFile = QtWidgets.QAction(MainWindow)
        self.actionSaveFile.setObjectName("actionSaveFile")
        self.actionSaveFile.triggered.connect(self.save_json_file)
        self.menuFIle.addAction(self.actionNew)
        self.menuFIle.addAction(self.actionLoad_Folder_Ctrl_L)
        self.menuFIle.addAction(self.actionSaveFile)
        self.menubar.addAction(self.menuFIle.menuAction())
        self.menubar.addAction(self.menuTutorials.menuAction())
        self.menubar.addAction(self.menuContact.menuAction())
        
        # Paint tool buttons
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setMaximumSize(QtCore.QSize(500, 60))
        self.widget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.widget.setAutoFillBackground(False)
        self.widget.setObjectName("widget")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout_2.setContentsMargins(9, -1, 9, -1)
        self.horizontalLayout_2.setSpacing(8)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.polygon_button = QtWidgets.QPushButton(self.widget)
        self.polygon_button.setMaximumSize(QtCore.QSize(40, 40))
        self.polygon_button.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/polygon_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.polygon_button.setIcon(icon1)
        self.polygon_button.setIconSize(QtCore.QSize(30, 30))
        self.polygon_button.setObjectName("polygon_button")
        self.horizontalLayout_2.addWidget(self.polygon_button)
        self.brush_button = QtWidgets.QPushButton(self.widget)
        self.brush_button.setMaximumSize(QtCore.QSize(40, 40))
        self.brush_button.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/brush_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.brush_button.setIcon(icon2)
        self.brush_button.setIconSize(QtCore.QSize(30, 30))
        self.brush_button.setObjectName("brush_button")
        self.horizontalLayout_2.addWidget(self.brush_button)
        # Bezier button
        self.bezier_button = QtWidgets.QPushButton(self.widget)
        self.bezier_button.setMaximumSize(QtCore.QSize(40, 40))
        self.bezier_button.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/bezier_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.bezier_button.setIcon(icon2)
        self.bezier_button.setIconSize(QtCore.QSize(30, 30))
        self.bezier_button.setObjectName("bezier_button")
        self.horizontalLayout_2.addWidget(self.bezier_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # isAdditive button
        self.isAdditive_button = QtWidgets.QPushButton(self.widget)
        self.isAdditive_button.setMaximumSize(QtCore.QSize(40, 40))
        self.isAdditive_button.setText("")        
        self.isAdditive_button_on_icon = QtGui.QIcon()
        self.isAdditive_button_on_icon.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/additive_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.isAdditive_button_off_icon = QtGui.QIcon()
        self.isAdditive_button_off_icon.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/additiveOFF_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.isAdditive_button.setIcon(self.isAdditive_button_on_icon)
        self.isAdditive_button.setIconSize(QtCore.QSize(30, 30))
        self.isAdditive_button.setObjectName("isAdditive_button")
        self.horizontalLayout_2.addWidget(self.isAdditive_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # isTopLayerOnly button
        self.isTopLayerOnly_button = QtWidgets.QPushButton(self.widget)
        self.isTopLayerOnly_button.setMaximumSize(QtCore.QSize(40, 40))
        self.isTopLayerOnly_button.setText("")        
        self.isTopLayerOnly_button_on_icon = QtGui.QIcon()
        self.isTopLayerOnly_button_on_icon.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/topmask_ON_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.isTopLayerOnly_button_off_icon = QtGui.QIcon()
        self.isTopLayerOnly_button_off_icon.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/topmask_OFF_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.isTopLayerOnly_button.setIcon(self.isTopLayerOnly_button_on_icon)
        self.isTopLayerOnly_button.setIconSize(QtCore.QSize(30, 30))
        self.isTopLayerOnly_button.setObjectName("isTopLayerOnly_button")
        self.horizontalLayout_2.addWidget(self.isTopLayerOnly_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # # Bucket button
        self.bucket_button = QtWidgets.QPushButton(self.widget)
        self.bucket_button.setMaximumSize(QtCore.QSize(40, 40))
        self.bucket_button.setText("")        
        icon_bucket = QtGui.QIcon()
        icon_bucket.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/bucket_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.bucket_button.setIcon(icon_bucket)
        self.bucket_button.setIconSize(QtCore.QSize(30, 30))
        self.bucket_button.setObjectName("bucket_button")
        self.horizontalLayout_2.addWidget(self.bucket_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # # binmask button
        self.binmask_button = QtWidgets.QPushButton(self.widget)
        self.binmask_button.setMaximumSize(QtCore.QSize(40, 40))
        self.binmask_button.setText("")        
        icon_binmask = QtGui.QIcon()
        icon_binmask.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/binmask_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.binmask_button.setIcon(icon_binmask)
        self.binmask_button.setIconSize(QtCore.QSize(30, 30))
        self.binmask_button.setObjectName("binmask_button")
        self.horizontalLayout_2.addWidget(self.binmask_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # # OpenFolder button
        self.openFolder_button = QtWidgets.QPushButton(self.widget)
        self.openFolder_button.setMaximumSize(QtCore.QSize(40, 40))
        self.openFolder_button.setText("")        
        icon_bucket = QtGui.QIcon()
        icon_bucket.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/openFolder_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.openFolder_button.setIcon(icon_bucket)
        self.openFolder_button.setIconSize(QtCore.QSize(30, 30))
        self.openFolder_button.setObjectName("openFolder_button")
        self.horizontalLayout_2.addWidget(self.openFolder_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # # Freehand button
        self.freehand_button = QtWidgets.QPushButton(self.widget)
        self.freehand_button.setMaximumSize(QtCore.QSize(40, 40))
        self.freehand_button.setText("")        
        icon_bucket = QtGui.QIcon()
        icon_bucket.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/freehand_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.freehand_button.setIcon(icon_bucket)
        self.freehand_button.setIconSize(QtCore.QSize(30, 30))
        self.freehand_button.setObjectName("freehand_button")
        self.horizontalLayout_2.addWidget(self.freehand_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # Edit images button
        self.editMode_button = QtWidgets.QPushButton(self.widget)
        self.editMode_button.setMaximumSize(QtCore.QSize(40, 40))
        self.editMode_button.setText("")        
        icon_binmask = QtGui.QIcon()
        icon_binmask.addPixmap(QtGui.QPixmap(jn(self.script_path,"icons/editFolder_icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.editMode_button.setIcon(icon_binmask)
        self.editMode_button.setIconSize(QtCore.QSize(30, 30))
        self.editMode_button.setObjectName("editMode_button")
        self.horizontalLayout_2.addWidget(self.editMode_button)
        self.gridLayout_2.addWidget(self.widget, 1, 2, 1, 1)
        # 
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        
        
        self.lobutton_label_blocks = [self.label_block_0]
        brush_settings["color"] = [0, 255, 0, 0]

        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "LivePyxel"))
        self.label_select_0.setText(_translate("MainWindow", "TextLabel"))
        self.label_6.setText(_translate("MainWindow", "Mask opacity"))
        self.btn_add.setText(_translate("MainWindow", "Add +"))
        self.btn_annotate.setText(_translate("MainWindow", "Annotate"))
        self.btn_capture.setText(_translate("MainWindow", "Capture \n"
"(Spacebar)"))
        self.btn_capture.setShortcut(_translate("MainWindow", "Space"))
        self.btn_switch_webcam.setText(_translate("MainWindow", "Switch Webcam\n"
"(Ctrl+1)"))
        self.btn_switch_webcam.setShortcut(_translate("MainWindow", "Ctrl+1"))
        self.Label_Categories.setText(_translate("MainWindow", "Label Categories"))
        self.menuFIle.setTitle(_translate("MainWindow", "FIle"))
        self.menuTutorials.setTitle(_translate("MainWindow", "Tutorials"))
        self.menuContact.setTitle(_translate("MainWindow", "Contact"))
        self.actionNew.setText(_translate("MainWindow", "New... (Ctrl+N)"))
        self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N"))
        self.actionLoad_Folder_Ctrl_L.setText(_translate("MainWindow", "Load Folder (Ctrl+L)"))
        self.actionLoad_Folder_Ctrl_L.setShortcut(_translate("MainWindow", "Ctrl+L"))
        self.actionSaveFile.setText(_translate("MainWindow", "Save File (Ctrl+S)"))
        self.actionSaveFile.setShortcut(_translate("MainWindow", "Ctrl+S"))

    def add_btn_block(self, label_text="New Label", color=None):
        # get the names of the color, label and edit buttons based on the value of index
        suffix = str(len(self.lobutton_label_blocks))
        
        
        # Create a new widget (btn_block)
        btn_block = QtWidgets.QWidget(self.scrollAreaWidgetContents_3)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
        btn_block.setSizePolicy(sizePolicy)
        btn_block.setMaximumSize(QtCore.QSize(16777215, 40))

        # Create a horizontal layout for the new block
        horizontal_layout = QtWidgets.QHBoxLayout(btn_block)

        # Create and add the label
        label = QtWidgets.QLabel(btn_block)
        label.setObjectName(f"label_select_{suffix}")
        label.setText(label_text)
        horizontal_layout.addWidget(label)

        # Create and add the color button
        color_button = QtWidgets.QPushButton(btn_block)
        color_button.setMaximumSize(QtCore.QSize(60, 16777215))
        if color is None:
                new_color = ",".join([str(random.randint(125,255)) for _ in range(3)])
                color_button.setStyleSheet(f"background-color: rgb({new_color});")
        else:
                color = ",".join(str(c) for c in color)
                color_button.setStyleSheet(f"background-color: rgb({color});")
        color_button.setObjectName(f"btn_select_{suffix}")
        horizontal_layout.addWidget(color_button)
        
        ############# EDIT BUTTON PROCEDURALLY GENERATED ###################
        # Create and add the edit button with an icon
        edit_button = QtWidgets.QPushButton(btn_block)
        edit_button.setMinimumSize(QtCore.QSize(20, 0))
        edit_button.setMaximumSize(QtCore.QSize(30, 16777215))
        # icon = QtGui.QIcon()
        # icon.addPixmap(QtGui.QPixmap(self.icon), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        edit_button.setIcon(self.icon_edit)
        edit_button.setObjectName(f"btn_edit_{suffix}")
        horizontal_layout.addWidget(edit_button)
        
        ############# TRASH BUTTON PROCEDURALLY GENERATED ###################
        # Create and add the trash button with an icon
        trash_button = QtWidgets.QPushButton(btn_block)
        trash_button.setMinimumSize(QtCore.QSize(20, 0))
        trash_button.setMaximumSize(QtCore.QSize(30, 16777215))
        # icon = QtGui.QIcon()
        # icon.addPixmap(QtGui.QPixmap(self.icon), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        trash_button.setIcon(self.icon_trash)
        trash_button.setObjectName(f"btn_remove_{suffix}")
        horizontal_layout.addWidget(trash_button)
        
        

        # Find the number of existing blocks (rows) in gridLayout_6 to determine the next available row
        row_position = self.gridLayout_6.rowCount()

        # Add the new block widget to the gridLayout_6 at the next available row
        self.gridLayout_6.addWidget(btn_block, row_position, 0, 1, 1)
        
        self.lobutton_label_blocks.append(btn_block)
        edit_button.clicked.connect(lambda: self.traverse_edit_buttons(edit_button))
        color_button.clicked.connect(lambda: self.traverse_select_buttons(color_button))
        trash_button.clicked.connect(lambda: self.traverse_remove_buttons(color_button))
        
        
    def traverse_remove_buttons(self,button):
        parent_widget = button.parent()
        for idx,w in enumerate(self.lobutton_label_blocks):
            if w == parent_widget:
                # print(label.objectName(),color_edit.objectName())
                
                dialog = QtWidgets.QDialog()
                ui_dialog = Ui_Dialog_Delete()
                ui_dialog.setupUi(dialog, idx, self.lobutton_label_blocks, button)
                # Execute the dialog and check if accepted or rejected
                result = dialog.exec_()
                # open the new edit widget and pass the elements

    # use the identity of the buttons edit pressed (edit buttons are located next to the color buttons in the label categories widget) 
    # to get parent information, to extract label and color buttons
    def traverse_edit_buttons(self, button):
        parent_widget = button.parent()
        for idx,w in enumerate(self.lobutton_label_blocks):
            if w == parent_widget:
                # extract the color button and the label
                label = parent_widget.findChild(QtWidgets.QLabel, f"label_select_{idx}")
                color_edit = parent_widget.findChild(QtWidgets.QPushButton, f"btn_select_{idx}")
                # print(label.objectName(),color_edit.objectName())
                
                dialog = QtWidgets.QDialog()
                ui_dialog = Ui_Dialog()
                ui_dialog.setupUi(dialog, label, color_edit)
                # Execute the dialog and check if accepted or rejected
                result = dialog.exec_()
                # open the new edit widget and pass the elements
                
        
    def traverse_select_buttons(self,button):
        global brushColor
        buttonStyle = button.styleSheet()
        buttonStyle = buttonStyle.replace(" ","")
        if "background-color:rgb" in buttonStyle:
            # buttonStyle = buttonStyle.replace(" ","") #remove empty spaces
            string_color = buttonStyle.split("background-color:rgb")[1] #extract everything after background-color
            string_color = string_color.split(";")[0] # keep everything before the end of the syle, defined by ;
            # turn digits into a tuple
            string_color = string_color[1:-1] #remove parenthesis
            string_color = string_color.split(",")
            colors = [int(c) for c in string_color]
            string_color = [colors[2],colors[1],colors[0]]
            # print(string_color)
            brush_settings["color"] = tuple(string_color) + (0,)
            # print(brush_settings["color"])
    def createSubfolders(self):
        os_settings["masks_path"] = jn(os_settings["directory"],"masks")
        os_settings["images_path"] = jn(os_settings["directory"],"images")
        if not os.path.exists(os_settings["masks_path"]):
            os.mkdir(os_settings["masks_path"])
        if not os.path.exists(os_settings["images_path"]):
            os.mkdir(os_settings["images_path"])
        
        
        
    
    def save_json_file(self):
        def get_color(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[0],colors[1],colors[2])
            return colors
        
        
        if os_settings["config"] != "":
            labels = []
            colors = []
            for idx,block in enumerate(self.lobutton_label_blocks):          
                label = block.findChild(QtWidgets.QLabel, f"label_select_{idx}")
                labels.append(label.text())
                color_edit = block.findChild(QtWidgets.QPushButton, f"btn_select_{idx}")
                colors.append(get_color(color_edit.styleSheet()))
                
            config = {
                "labels":labels,
                "colors":colors
            }
            
            with open(os_settings["config"],"w") as jsonfile:
                json.dump(config, jsonfile, indent=4)  # Use json.dump to write the dictionary to the file
            QtWidgets.QMessageBox.information(None, "Success!!!", f"The project has been saved")
        else:
            QtWidgets.QMessageBox.critical(None,"Project couldn't be saved", "It seems no config file has been selected.\nThis is probably caused by a missing path to the config.json file.\nPlease create or load a project first.")
            
    def new_file_dialog(self):
        options = QtWidgets.QFileDialog.Options()
        directory = QtWidgets.QFileDialog.getExistingDirectory(None, "Select Folder", "", options=options)
        if directory:
            # !!! system shouldn't be set before asking user to work around config.json file (i.e. no os_settings)
            os_settings["directory"] = directory
            os_settings["config"] = jn(directory, "config.json")
            
            if os.path.exists(os_settings["config"]):
                QtWidgets.QMessageBox.information(None, "A config file was found in the folder selected", f"A config.json file seems to already exist in the location \n\n{os_settings['config']}.\n\nPlease make sure to erase all data if you want to use this location, and try again")
            else:
                self.save_json_file()
                self.createSubfolders()
                QtWidgets.QMessageBox.information(None, "Success!!", f"A new project project has been created in the directory: {directory}")
                    # You can add additional code here to handle the new file creation        
        
        
    def clear_layout(self):
        for i in reversed(range(self.gridLayout_6.count())): 
            widget = self.gridLayout_6.itemAt(i).widget()
            if widget is not None: 
                widget.deleteLater()  # Properly delete the widget
            self.gridLayout_6.removeItem(self.gridLayout_6.itemAt(i))
        self.lobutton_label_blocks = []
                
    def load_file_dialog(self):
        options = QtWidgets.QFileDialog.Options()
        file_name, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, 
            "Select JSON File", 
            "", 
            "JSON Files (*.json);;All Files (*)", 
            options=options
        )
        
        if file_name:
            if os.path.exists(file_name):
                with open(file_name, "r") as jsonfile:
                    config = json.load(jsonfile)
                    labels = config.get("labels", [])
                    colors = config.get("colors", [])

                # cv2 understands colors as  BGR
                # bgr_colors = []
                # for color in colors:
                #     # Swap R and B channels (assuming color is [R,G,B])
                #     bgr_color = [color[2], color[1], color[0]]
                #     bgr_colors.append(bgr_color)
                    
                self.clear_layout()
                for idx in range(len(labels)):
                    self.add_btn_block(labels[idx],colors[idx])
                QtWidgets.QMessageBox.information(None, "Success!!", f"The information from the previous session has been successfully loaded")
                os_settings["config"] = file_name
                os_settings["masks_path"] = jn(os.path.split(file_name)[0],"masks")
                os_settings["images_path"] = jn(os.path.split(file_name)[0],"images")
                print(os_settings["images_path"])
                print(os_settings["masks_path"])

            else:
                print("Selected file not found.")
        else:
            print("No file selected.")

    
# DD. DISPLAY_WIDGET
# displayWidget = WebcamWidget(QLabel)
# interp. a child class optimized for event controlling
class WebcamWidget(QtWidgets.QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        custom_cursor_pixmap_polygon = QtGui.QPixmap("./icons/bright_cross_cursor.png")  # Ensure you have a bright cursor image
        self.custom_cursor_polygon = QtGui.QCursor(custom_cursor_pixmap_polygon)
        self.setMouseTracking(True)

    def enterEvent(self, event):
        """Hide the cursor when the mouse enters the widget."""
        if brush_settings["is_brush_mode"] == "brush":
            self.setCursor(Qt.BlankCursor)
        elif brush_settings["is_brush_mode"] == "polygon" or brush_settings["is_brush_mode"] == "bezier":
            self.setCursor(self.custom_cursor_polygon)
        cursor_settings["in_display"] = True

    def leaveEvent(self, event):
        """Restore the cursor when the mouse leaves the widget."""
        self.setCursor(Qt.ArrowCursor)
        cursor_settings["in_display"] = False

    
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


