from PyQt5 import QtWidgets, uic
import sys
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QApplication, QDialog
from lrm.exceptions import lrm_slot, lrm_slot_param
import xml.etree.ElementTree as ET
from enum import Enum


class Tags(Enum):
    TEXT_TAG = "TextTag"
    ICON_TAG = "IconTag"
    TEXTTOOL_TAG = "TextToolTag"
    OR_TAG = "OrTag"
    PLACEHOLDER_TAG = "PlaceHolderTag"
    BUTTON_TAG = "Button"
    SETBOX_TAG = "SetBox"
    CHECK_BOX_TAG = "CheckBox.create"
    PARAM_CIRULAR_TAG = "ParamCircular.create"
    CREATE_NEW_MASK = "Create new mask"
    SELECT_EXISTING_MASK = "Select existing mask"


class OrTagDialog(QtWidgets.QDialog):
    def __init__(self, or_tag_receive) -> None:
        super().__init__()
        # self.parent = parent

        self.ui7 = uic.loadUi("UI_FILES/OrTagDialog.ui", self)
        self.ui7.setWindowTitle("Add Or Tag")
        self.setModal(True)
        self.load_everything()
        self.show()
        self.ui7.finished.connect(self.dialog_finished)
        self.or_tag_receive = or_tag_receive
        self.elements = []
    
    @lrm_slot_param
    def dialog_finished(self, result):
        if result == QDialog.Rejected:
            # user clicked "Cancel" or closed the dialog
            # handle cancellation here
            pass
        else:
            # user clicked "OK"
            # handle acceptance here
            self.on_accept_dialog_window()
    
    @lrm_slot
    def on_accept_dialog_window(self):
        tag_actions = {
            Tags.TEXT_TAG.value: self.text_tag_save,
            Tags.ICON_TAG.value: self.icon_tag_save,
            Tags.TEXTTOOL_TAG.value: self.textool_tag_save,
            Tags.PLACEHOLDER_TAG.value: self.placeholder_tag_save}
        
        action = tag_actions.get(self.tags_combo_box.currentText())
        
        if action:
            action()
            self.or_tag_receive(self.elements)
        else:
            QMessageBox.warning(self, "Error", "You need to fill all required fields.")
            self.show()
    
    @lrm_slot
    def load_everything(self):
        # It's needed to connect these two buttons with actions.
        self.icon_tag.clicked.connect(self.open_icon_tag_file_dialog)
        self.textool_tag.clicked.connect(self.open_textool_tag_file_dialog)

        # Load every labels so that we can work with it.
        LABELS = [
                    ("TextTagLabel", "text_tag_label"),
                    ("MethodTagLabel", "method_tag_label"),
                    ("ThresholdTagLabel", "threshold_tag_label"),
                    ("IconTagLabel", "icon_tag_label"),
                    ("TextToolTagLabel", "textool_tag_label"),
                    ("KeyTagLabel", "key_tag_label"),
                    ("PreprocessingModeTagLabel", "preprocessing_mode_tag_label")
        ]

        self.modifiable_elements = [self.text_tag,
        self.method_tag,
        self.threshold_tag,
        self.icon_tag,
        self.textool_tag,
        self.key_tag,
        self.preprocessing_mode_tag] + [self.text_tag_label, 
                                        self.method_tag_label, 
                                        self.threshold_tag_label,
                                        self.icon_tag_label,
                                        self.textool_tag_label,
                                        self.key_tag_label,
                                        self.preprocessing_mode_tag_label]

        # Make it invisible at first to just hide it until we need it.
        for element in self.modifiable_elements:
            element.setVisible(False)

        # This is needed for functions that make the tags and labels visible afterwards.
        self.persistent_elements = None
        
        self.tags_combo_box.setCurrentIndex(-1)
        self.tags_combo_box.currentIndexChanged.connect(self.display_tags_combo_box_option)

    @lrm_slot
    def display_tags_combo_box_option(self):
        turn_visible = []
        self.persistent_elements = None

        if self.tags_combo_box.currentText() == Tags.TEXT_TAG.value:
            # Make these visible
            turn_visible = [self.text_tag,
            self.text_tag_label,
            self.method_tag,
            self.method_tag_label,
            self.threshold_tag,
            self.threshold_tag_label]

        elif self.tags_combo_box.currentText() == Tags.ICON_TAG.value:
            # Make these visible
            turn_visible = [self.icon_tag,
            self.icon_tag_label]     

        elif self.tags_combo_box.currentText() == Tags.TEXTTOOL_TAG.value:
            # Make these visible
            turn_visible = [self.textool_tag,
            self.textool_tag_label,
            self.threshold_tag,
            self.threshold_tag_label]
        
        elif self.tags_combo_box.currentText() == Tags.PLACEHOLDER_TAG.value:
            # Make these visible
            turn_visible = [self.key_tag,
            self.key_tag_label,
            self.preprocessing_mode_tag,
            self.preprocessing_mode_tag_label]

        for element in self.modifiable_elements:
            element.setVisible(False)
        for element in turn_visible:
            element.setVisible(True)


    def text_tag_save(self):
        if len(self.text_tag.text()) > 0 and len(self.method_tag.text()) > 0 and self.threshold_tag.value() > 0:
            self.elements.append(Tags.TEXT_TAG.value)
            self.elements.append({"text": self.text_tag.text()})
            self.elements.append({"method": self.method_tag.text()})
            self.elements.append({"threshold": self.threshold_tag.value()})
            return True

        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    def icon_tag_save(self):
        if len(self.icon_tag.text()) > 1:
            self.elements.append(Tags.ICON_TAG.value)
            self.elements.append({"icon": self.icon_tag.text()})
            return True
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    def textool_tag_save(self):
        if len(self.textool_tag.text()) > 1 and self.threshold_tag.value() > 0:
            self.elements.append(Tags.TEXTTOOL_TAG.value)
            self.elements.append({"texttool": self.textool_tag.text()})
            self.elements.append({"threshold": self.threshold_tag.value()})
            return True
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()

    def placeholder_tag_save(self):
        if len(self.key_tag.text()) > 0 and len(self.preprocessing_mode_tag.text()) > 0:
            self.elements.append(Tags.PLACEHOLDER_TAG.value)
            self.elements.append({"key": self.key_tag.text()})
            self.elements.append({"preprocessing_mode": self.preprocessing_mode_tag.text()})
            return True
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    @lrm_slot
    def open_icon_tag_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.icon_tag_file_name, _ = QFileDialog.getOpenFileName(self,"Select Image", "","Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options) # Self substitute for self.parent afterwards
        if self.icon_tag_file_name:
            self.icon_tag.setText(self.icon_tag_file_name.split('/')[-1])

    @lrm_slot
    def open_textool_tag_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.textool_file_name, _ = QFileDialog.getOpenFileName(self,"Select existing mask", "","XML Files (*.xml);;All Files (*)", options=options) # Self argument needs to be changed later to self.parent
        if self.textool_file_name:
            tree = ET.parse(self.textool_file_name)
            root = tree.getroot()
            if root.tag == "LangDef":
                self.textool_tag.setText(self.textool_file_name.split('/')[-1])
            else:
                QMessageBox.warning(self, "Error", "You selected a file that doesn't correspond to the normal .xml text tool format! Try again!")
                self.open_textool_tag_file_dialog()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    UIWindow = OrTagDialog()
    app.exec_()