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
import json
from enum import Enum
from OrTagDialog import OrTagDialog
from NewIconDialog import NewIcon


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 Property(QtWidgets.QDialog):

    def __init__(self, parent, rectangle, cancel_event, mask_to_rectangle, save_new_mask_to_xml, screenshot_file_name) -> None:
        super().__init__()

        self.ui6 = uic.loadUi("UI_FILES/New_Rectangle_Release_All.ui", self)
        self.ui6.setWindowTitle("Add Elements")
        self.setModal(True)
        self.rectangle = rectangle
        self.cancel_event = cancel_event
        self.parent = parent
        self.mask_to_rectangle = mask_to_rectangle
        self.screenshot_file_name = screenshot_file_name
        self.load_and_populate_tag_combobox()
        self.elements = {}
        self.load_everything()
        self.save_new_mask_to_xml = save_new_mask_to_xml
        self.or_tags = []

        self.ui6.buttonBox.accepted.connect(self.dialog_accepted)
        self.ui6.buttonBox.rejected.connect(self.dialog_rejected)
    
    @lrm_slot
    def dialog_accepted(self):
        self.on_accept_dialog_window()
    
    @lrm_slot
    def dialog_rejected(self):
        self.cancel_event()
        self.close()

    @lrm_slot_param
    def feed_existing_data(self, mask_name, data):
        self.elements = data
        for key in self.elements:
            tag = self.elements[key][0]

        self.tag_combo_box.setCurrentText(tag)
        self.mask_combo_box.setCurrentText(Tags.SELECT_EXISTING_MASK.value)
        self.existing_mask_button.setText(mask_name)

        for key in self.elements:
            for element in self.elements[key]:
                if isinstance(element, dict):
                    json_key = list(element.keys())[0]
                    if json_key in self.load_data_dict:
                        for second_element in self.load_data_dict[json_key]:
                            second_element.setVisible(True)
                        if self.load_data_dict[json_key][0] == self.identification_tag:
                            pass
                            # self.identification_tag.setCurrentText(element[json_key])
                        elif self.load_data_dict[json_key][0] == self.threshold_tag:
                            self.load_data_dict[json_key][0].setValue(float(element[json_key]))
                        elif self.load_data_dict[json_key][0] == self.values_tag or self.load_data_dict[json_key][0] == self.value_identificators_tag:
                            self.load_data_dict[json_key][0].setText(", ".join(element[json_key]))
                        elif self.load_data_dict[json_key][0] == self.or_tag_text_edit:
                            self.load_data_dict[json_key][0].setText(str(element[json_key]))
                            self.or_tag_text_edit.setReadOnly(False)
                        else:
                            print(f"LOADING {element[json_key]}")
                            self.load_data_dict[json_key][0].setText(element[json_key])
    
    @lrm_slot_param
    def dialog_finished(self, result):
        if result == QDialog.Accepted:
            # user clicked "OK"
            # handle acceptance here
            self.on_accept_dialog_window()
        else:
            # user clicked "Cancel" or closed the dialog
            # handle cancellation here
            self.cancel_event()
        self.close()
    
    @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.OR_TAG.value: self.or_tag_save,
            Tags.PLACEHOLDER_TAG.value: self.placeholder_tag_save,
            Tags.BUTTON_TAG.value: self.button_or_set_box_save,
            Tags.SETBOX_TAG.value: self.button_or_set_box_save,
            Tags.PARAM_CIRULAR_TAG.value: self.param_circular_save,
            Tags.CHECK_BOX_TAG.value: self.checkbox_save
        }
        if self.tag_combo_box.currentText() == "":
            QMessageBox.warning(self, "Error", "You need to fill all required fields.")
            self.show()
        else:
            action = tag_actions.get(self.tag_combo_box.currentText())
            if action():
                self.mask_to_rectangle()
                self.close()

    @lrm_slot
    def load_rectangle(self):
        mask_key = self.new_mask_line_edit.text()
        mask_data = {"OffsetX": int(self.rectangle.rect().x()),
                    "OffsetY": int(self.rectangle.rect().y()),
                    "SizeX": int(self.rectangle.rect().width()),
                    "SizeY": int(self.rectangle.rect().height())}
        self.elements[self.action_key] = [elem for elem in self.elements[self.action_key] if "Mask" not in elem]
        self.elements[self.action_key].append({"Mask": {mask_key: mask_data}})
        self.save_new_mask_to_xml(*mask_data.values(), self.new_mask_line_edit.text())

    def load_tags_json(self):
        tags_list = []
        with open("configs/Tags.json") as tags:
            tags = json.load(tags)

        for key, _ in tags.items():
            tags_list.append(key)
        
        return tags_list
    
    def load_tags_for_elements_json(self):
        tags_list = []
        with open("configs/Tags.json") as tags:
            tags = json.load(tags)

        for key, _ in tags.items():
            if key == Tags.BUTTON_TAG.value or key == Tags.SETBOX_TAG.value or key == Tags.CHECK_BOX_TAG.value or key == Tags.PARAM_CIRULAR_TAG.value:
                continue
            else:
                tags_list.append(key)
        
        return tags_list

    def load_and_populate_tag_combobox(self):
        self.tag_combo_box.clear()
        self.tag_combo_box.addItems(self.load_tags_json())
        self.tag_combo_box.setCurrentIndex(-1)
        self.tag_combo_box.currentIndexChanged.connect(self.load_identification_element_units_json)
        self.tag_combo_box.currentIndexChanged.connect(self.display_tag_combo_box_option)
        self.tag_combo_box.currentIndexChanged.connect(self.mask_actions)

    def load_identification_element_units_json(self):
        """This method is only for determining if it's element or identification and that adds this information to self.elements."""
        with open("configs/IdentificationElementUnits.json") as idents:
            idents = json.load(idents)
        
        if self.tag_combo_box.currentText() in idents["Identification"]:
            if "Element" in self.elements:
                self.elements["Identification"] = self.elements.pop("Element")
            self.action_key = "Identification"
        else:
            if "Identification" in self.elements:
                self.elements["Element"] = self.elements.pop("Identification")
            self.action_key = "Element"
        
        if not self.action_key in self.elements:
            self.elements[self.action_key] = []
    
    def display_tag_combo_box_option(self):
        turn_visible = []
        self.persistent_elements = None

        if self.tag_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.tag_combo_box.currentText() == Tags.ICON_TAG.value:
            # Make these visible
            turn_visible = [self.icon_tag_existing,
            self.icon_tag_new,
            self.icon_tag_label,
            self.existing_icon_label,
            self.new_icon_label]     

        elif self.tag_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.tag_combo_box.currentText() == Tags.OR_TAG.value:
            turn_visible = [self.or_tag_button,
            self.or_tag_text_edit,
            self.or_tag_label]
        
        elif self.tag_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]
        
        elif self.tag_combo_box.currentText() == Tags.BUTTON_TAG.value:
            # Make these visible
            turn_visible = [self.name_tag,
            self.name_tag_label,
            self.identification_tag,
            self.identification_tag_label,
            self.target_screen_tag,
            self.target_screen_tag_label]

        elif self.tag_combo_box.currentText() == Tags.SETBOX_TAG.value:
            # Make these visible
            turn_visible = [self.name_tag,
            self.name_tag_label,
            self.identification_tag,
            self.identification_tag_label,
            self.target_screen_tag,
            self.target_screen_tag_label]
        
        elif self.tag_combo_box.currentText() == Tags.PARAM_CIRULAR_TAG.value:
            turn_visible = [self.name_tag,
            self.name_tag_label,
            self.identification_tag,
            self.element_identification_tag_label,
            self.values_tag,
            self.values_label,
            self.value_identificators_tag,
            self.value_identificators_label,
            self.threshold_tag,
            self.threshold_tag_label]

        elif self.tag_combo_box.currentText() == Tags.CHECK_BOX_TAG.value:
            turn_visible = [self.name_tag,
            self.name_tag_label,
            self.identification_tag,
            self.element_identification_tag_label,
            self.false_identification_tag,
            self.false_identification_tag_label,
            self.true_identification_tag,
            self.true_identification_tag_label,
            self.threshold_tag,
            self.threshold_tag_label]

        for element in self.modifiable_elements:
            element.setVisible(False)
        for element in turn_visible:
            element.setVisible(True)
    
    def display_button_or_set_box_option(self):
        turn_visible = []
        if self.persistent_elements is None:
            self.persistent_elements = [element for element in self.modifiable_elements if element.isVisible()]

        if self.identification_tag.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.identification_tag.currentText() == Tags.ICON_TAG.value:
            # Make these visible
            turn_visible = [self.icon_tag_existing,
            self.icon_tag_new,
            self.icon_tag_label,
            self.existing_icon_label,
            self.new_icon_label]

        elif self.identification_tag.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.identification_tag.currentText() == Tags.OR_TAG.value:
            turn_visible = [self.or_tag_button,
            self.or_tag_text_edit,
            self.or_tag_label]

        elif self.identification_tag.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)
        for element in self.persistent_elements:
            element.setVisible(True)
    
    @lrm_slot
    def mask_actions(self):
        self.mask_label.setVisible(True)
        self.mask_combo_box.setVisible(True)

        # Initialize mask combo box
        self.mask_combo_box.setCurrentIndex(-1)

        # Initialize line edit for new mask name.
        self.new_mask_line_edit.setVisible(False)
        self.mask_name_label.setVisible(False)

        # Connect button
        self.existing_mask_button.setVisible(False)
        self.existing_mask_button.clicked.connect(self.open_mask_file_dialog)

        self.mask_combo_box.currentIndexChanged.connect(self.mask_name_visible_invisible)

    def mask_name_visible_invisible(self):
        if self.mask_combo_box.currentText() == "Select existing mask":
            self.mask_name_label.setVisible(True)
            self.existing_mask_button.setVisible(True)
            self.new_mask_line_edit.setVisible(False)
        else:
            self.mask_name_label.setVisible(True)
            self.new_mask_line_edit.setVisible(True)
            self.existing_mask_button.setVisible(False)

    @lrm_slot
    def open_mask_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.mask_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.mask_file_name:
            tree = ET.parse(self.mask_file_name)
            root = tree.getroot()
            element = root.find(".//ELEMENT")
            if element is not None:
                elements = {}
                elements["Mask"] = {}
                elements["Mask"][root.attrib["name"]] = {}
                elements["Mask"][root.attrib["name"]]["OffsetX"] = int(element.find("OffsetX").text)
                elements["Mask"][root.attrib["name"]]["OffsetY"] = int(element.find("OffsetY").text)
                elements["Mask"][root.attrib["name"]]["SizeX"] = int(element.find("SizeX").text)
                elements["Mask"][root.attrib["name"]]["SizeY"] = int(element.find("SizeY").text)
                for dictionary in self.elements[self.action_key]:
                    for dict_key in dictionary:
                        if dict_key == "Mask":
                            self.elements[self.action_key].remove(dictionary)
                self.elements[self.action_key].append(elements)
                self.existing_mask_button.setText(self.mask_file_name.split('/')[-1])
            else:
                QMessageBox.warning(self, "Error", "You selected a file that doesn't correspond to the normal .xml mask format! Try again!")
                self.open_mask_file_dialog()

    def remove_old_dictionaries_from_list(self, *args):
        items_to_pop = []
        for index, dictionary in enumerate(self.elements[self.action_key]):
            if isinstance(dictionary, dict):
                for dictionary_key in dictionary:
                    if len(args) == 0:
                        if dictionary_key == "Mask":
                            continue
                        else:
                            items_to_pop.append(dictionary)
                    elif args[0] == dictionary_key:
                        items_to_pop.append(dictionary)
        
        self.elements[self.action_key] = [x for x in self.elements[self.action_key] if x not in items_to_pop]

    def text_tag_save(self):
        if self.mask_combo_box.currentText() == Tags.CREATE_NEW_MASK.value:
            if len(self.text_tag.text()) > 0 and len(self.method_tag.text()) > 0 and len(self.new_mask_line_edit.text()) > 0  and self.threshold_tag.value() > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"text": self.text_tag.text()})
                self.elements[self.action_key].append({"method": self.method_tag.text()})
                self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True

            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        elif self.mask_combo_box.currentText() == Tags.SELECT_EXISTING_MASK.value:
            if len(self.text_tag.text()) > 0 and len(self.method_tag.text()) > 0 and len(self.existing_mask_button.text()) > 1  and self.threshold_tag.value() > 0:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"text": self.text_tag.text()})
                self.elements[self.action_key].append({"method": self.method_tag.text()})
                self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True

            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    def icon_tag_save(self):
        if self.mask_combo_box.currentText() == Tags.CREATE_NEW_MASK.value:
            if len(self.icon_tag_existing.text()) > 1 and len(self.new_mask_line_edit.text()) > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"icon": self.icon_tag_existing.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            
            elif len(self.icon_tag_new.text()) > 1 and len(self.new_mask_line_edit.text()) > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"icon": self.icon_tag_new.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        elif self.mask_combo_box.currentText() == Tags.SELECT_EXISTING_MASK.value:
            if len(self.icon_tag_existing.text()) > 1 and len(self.existing_mask_button.text()) > 1:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"icon": self.icon_tag_existing.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            
            elif len(self.icon_tag_new.text()) > 1 and len(self.existing_mask_button.text()) > 1:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"icon": self.icon_tag_new.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    def textool_tag_save(self):
        if self.mask_combo_box.currentText() == Tags.CREATE_NEW_MASK.value:
            if len(self.textool_tag.text()) > 1 and len(self.new_mask_line_edit.text()) > 0 and self.threshold_tag.value() > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"texttool": self.textool_tag.text()})
                self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        elif self.mask_combo_box.currentText() == Tags.SELECT_EXISTING_MASK.value:
            if len(self.textool_tag.text()) > 1 and len(self.existing_mask_button.text()) > 1 and self.threshold_tag.value() > 0:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"texttool": self.textool_tag.text()})
                self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    @lrm_slot
    def or_tag_save(self):
        if self.mask_combo_box.currentText() == Tags.CREATE_NEW_MASK.value:
            if len(self.or_tag_text_edit.toPlainText()) > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"OrTag": self.or_tags})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        elif self.mask_combo_box.currentText() == Tags.SELECT_EXISTING_MASK.value:
            if len(self.or_tag_text_edit.toPlainText()) > 0:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"OrTag": self.or_tags})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()

    def placeholder_tag_save(self):
        if self.mask_combo_box.currentText() == Tags.CREATE_NEW_MASK.value:
            if len(self.key_tag.text()) > 0 and len(self.preprocessing_mode_tag.text()) > 0 and len(self.new_mask_line_edit.text()) > 0:
                self.load_rectangle()
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"key": self.key_tag.text()})
                self.elements[self.action_key].append({"preprocessing_mode": self.preprocessing_mode_tag.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        elif self.mask_combo_box.currentText() == Tags.SELECT_EXISTING_MASK.value:
            if len(self.key_tag.text()) > 0 and len(self.preprocessing_mode_tag.text()) > 0 and len(self.existing_mask_button.text()) > 1:
                self.remove_old_dictionaries_from_list()
                self.elements[self.action_key].append({"key": self.key_tag.text()})
                self.elements[self.action_key].append({"preprocessing_mode": self.preprocessing_mode_tag.text()})
                if isinstance(self.elements[self.action_key][0], str):
                    self.elements[self.action_key].pop(0)
                self.elements[self.action_key].insert(0, self.tag_combo_box.currentText())
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    def button_or_set_box_save(self):
        if len(self.name_tag.text()) > 0:
            if self.identification_tag.currentText() == Tags.ICON_TAG.value and self.icon_tag_save():
                self.help_button_or_set_box_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXT_TAG.value and self.text_tag_save():
                self.help_button_or_set_box_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXTTOOL_TAG.value and self.textool_tag_save():
                self.help_button_or_set_box_save()
                return True
            elif self.identification_tag.currentText() == Tags.OR_TAG.value and self.or_tag_save():
                self.help_button_or_set_box_save()
                return True
            elif self.identification_tag.currentText() == Tags.PLACEHOLDER_TAG.value and self.placeholder_tag_save():
                self.help_button_or_set_box_save()
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
                return False

        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
            return False
    
    @lrm_slot
    def help_button_or_set_box_save(self):
        self.remove_old_dictionaries_from_list("name")
        self.elements[self.action_key].append({"name": self.name_tag.text()})
        self.remove_old_dictionaries_from_list("identification_tag")
        self.elements[self.action_key].append({"identification_tag": self.identification_tag.currentText()})
        if len(self.target_screen_tag.text()) > 0:
            self.remove_old_dictionaries_from_list("target_screen")
            self.elements[self.action_key].append(({"target_screen": self.target_screen_tag.text()}))
    
    def param_circular_save(self):
        if len(self.name_tag.text()) > 0 and len(self.values_tag.text()) > 0 and len(self.value_identificators_tag.text()) > 0 and self.threshold_tag.value() > 0:
            if self.identification_tag.currentText() == Tags.ICON_TAG.value and self.icon_tag_save():
                self.help_param_circular_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXT_TAG.value and self.text_tag_save():
                self.help_param_circular_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXTTOOL_TAG.value and self.textool_tag_save():
                self.help_param_circular_save()
                return True
            elif self.identification_tag.currentText() == Tags.OR_TAG.value and self.or_tag_save():
                self.help_param_circular_save()
                return True
            elif self.identification_tag.currentText() == Tags.PLACEHOLDER_TAG.value and self.placeholder_tag_save():
                self.help_param_circular_save()
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()

    @lrm_slot
    def help_param_circular_save(self):
        self.remove_old_dictionaries_from_list("name")
        self.elements[self.action_key].append({"name": self.name_tag.text()})
        self.remove_old_dictionaries_from_list("threshold")
        self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
        self.remove_old_dictionaries_from_list("values")
        self.elements[self.action_key].append({"values": self.values_tag.text().split(", ")})
        self.remove_old_dictionaries_from_list("value_identificators")
        self.elements[self.action_key].append({"value_identificators": self.value_identificators_tag.text().split(", ")})
        self.remove_old_dictionaries_from_list("element_identification_tag")
        self.elements[self.action_key].append({"element_identification_tag": self.identification_tag.currentText()})

    def checkbox_save(self):
        if len(self.name_tag.text()) > 0 and len(self.false_identification_tag.text()) > 0 and len(self.true_identification_tag.text()) > 0 and self.threshold_tag.value() > 0:
            if self.identification_tag.currentText() == Tags.ICON_TAG.value and self.icon_tag_save():
                self.help_checkbox_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXT_TAG.value and self.text_tag_save():
                self.help_checkbox_save()
                return True
            elif self.identification_tag.currentText() == Tags.TEXTTOOL_TAG.value and self.textool_tag_save():
                self.help_checkbox_save()
                return True
            elif self.identification_tag.currentText() == Tags.OR_TAG.value and self.or_tag_save():
                self.help_checkbox_save()
                return True
            elif self.identification_tag.currentText() == Tags.PLACEHOLDER_TAG.value and self.placeholder_tag_save():
                self.help_checkbox_save()
                return True
            else:
                QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
                self.show()
        else:
            QMessageBox.warning(self, "Error", "Please fill in all displayed fields.")
            self.show()
    
    @lrm_slot
    def help_checkbox_save(self):
        self.remove_old_dictionaries_from_list("name")
        self.elements[self.action_key].append({"name": self.name_tag.text()})
        self.remove_old_dictionaries_from_list("threshold")
        self.elements[self.action_key].append({"threshold": self.threshold_tag.value()})
        self.remove_old_dictionaries_from_list("element_identification_tag")
        self.elements[self.action_key].append({"element_identification_tag": self.identification_tag.currentText()})
        self.remove_old_dictionaries_from_list("false_identification_tag")
        self.elements[self.action_key].append({"false_identification_tag": self.false_identification_tag.text()})
        self.remove_old_dictionaries_from_list("true_identification_tag")
        self.elements[self.action_key].append({"true_identification_tag": self.false_identification_tag.text()})

    @lrm_slot
    def load_everything(self):
        """Load all the modifiable elements, make them invisible and connect buttons to their methods."""

        self.modifiable_elements = [self.text_tag,
        self.name_tag,
        self.method_tag,
        self.threshold_tag,
        self.icon_tag_existing,
        self.icon_tag_new,
        self.textool_tag,
        self.key_tag,
        self.preprocessing_mode_tag,
        self.identification_tag,
        self.target_screen_tag,
        self.values_tag,
        self.value_identificators_tag,
        self.false_identification_tag,
        self.true_identification_tag,
        self.or_tag_button,
        self.or_tag_text_edit] + [self.text_tag_label,
                                  self.name_tag_label,
                                  self.method_tag_label,
                                  self.threshold_tag_label,
                                  self.icon_tag_label,
                                  self.existing_icon_label,
                                  self.new_icon_label,
                                  self.textool_tag_label,
                                  self.key_tag_label,
                                  self.preprocessing_mode_tag_label,
                                  self.identification_tag_label,
                                  self.target_screen_tag_label,
                                  self.element_identification_tag_label,
                                  self.values_label,
                                  self.value_identificators_label,
                                  self.false_identification_tag_label,
                                  self.true_identification_tag_label,
                                  self.or_tag_label]

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

        # This is needed for functions that make the tags and labels visible afterwards.
        self.persistent_elements = None

        # I need to connect two buttons with actions.
        self.icon_tag_existing.clicked.connect(self.open_icon_tag_file_dialog)
        self.icon_tag_new.clicked.connect(lambda: NewIcon(self.screenshot_file_name, self.receive_png_name))
        self.textool_tag.clicked.connect(self.open_textool_tag_file_dialog)

        # Connect or tag button to another dialog window.
        self.or_tag_button.clicked.connect(self.or_tag_dialog)

        # I need to load the identification tag combo box.
        self.populate_identification_tag_combobox()

        # This dictionary is for when you're loading data from json and want to feed dialog window.
        self.load_data_dict = {"icon": [self.icon_tag_existing, self.icon_tag_label],
                               "name": [self.name_tag, self.name_tag_label],
                               "identification_tag": [self.identification_tag, self.identification_tag_label],
                               "threshold": [self.threshold_tag, self.threshold_tag_label],
                               "texttool": [self.textool_tag, self.textool_tag_label],
                               "key": [self.key_tag, self.key_tag_label],
                               "preprocessing_mode": [self.preprocessing_mode_tag, self.preprocessing_mode_tag_label],
                               "text": [self.text_tag, self.text_tag_label],
                               "method": [self.method_tag, self.method_tag_label],
                               "target_screen": [self.target_screen_tag, self.target_screen_tag_label],
                               "element_identification_tag": [self.identification_tag, self.element_identification_tag_label],
                               "values": [self.values_tag, self.values_label],
                               "value_identificators": [self.value_identificators_tag, self.value_identificators_label],
                               "false_identification_tag": [self.false_identification_tag, self.false_identification_tag_label],
                               "true_identification_tag": [self.true_identification_tag, self.true_identification_tag_label],
                               "OrTag": [self.or_tag_text_edit, self.or_tag_label]} 
    
    @lrm_slot
    def or_tag_dialog(self):
        self.or_tag_dialog = OrTagDialog(self.or_tag_receive)
    
    @lrm_slot_param
    def or_tag_receive(self, elements):
        self.or_tags.append(elements)
        self.or_tag_text_edit.clear()
        self.or_tag_text_edit.setText(str(self.or_tags))
        self.or_tag_text_edit.setReadOnly(False)

    @lrm_slot
    def populate_identification_tag_combobox(self):
        self.identification_tag.clear()
        self.identification_tag.addItems(self.load_tags_for_elements_json())
        self.identification_tag.setCurrentIndex(-1)
        self.identification_tag.currentIndexChanged.connect(self.display_button_or_set_box_option)

    @lrm_slot
    def open_icon_tag_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.icon_tag_existing_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_existing_file_name:
            self.icon_tag_existing.setText(self.icon_tag_existing_file_name.split('/')[-1])
            self.icon_tag_new.setVisible(False)
            self.new_icon_label.setVisible(False)

    @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()
    
    @lrm_slot_param
    def receive_png_name(self, new_screenshot_name):
        self.icon_tag_new.setText(new_screenshot_name)
        self.icon_tag_existing.setVisible(False)
        self.existing_icon_label.setVisible(False)


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