from Qt import QtCore, QtWidgets


class RezModifierDialog(QtWidgets.QDialog):
    def __init__(self, app_name, text_packages, rez_modifiers=None, rez_modifier_is_used=False,
                 parent=None):
        super(RezModifierDialog, self).__init__(parent)
        self.app_name = app_name
        self.text_packages = text_packages
        self.rez_modifier_is_used = rez_modifier_is_used
        if rez_modifiers is None:
            self.rez_modifiers = []
        else:
            self.rez_modifiers = rez_modifiers
        self._create_ui()
        self._post_data_to_editor()

    def _create_ui(self):
        self.setWindowTitle("Change REZ Request | %s" % self.app_name)
        self.setLayout(QtWidgets.QVBoxLayout())
        self.setFixedWidth(450)

        label_shower = QtWidgets.QLabel("Packages:")
        self.shower = QtWidgets.QTextEdit(self)
        self.shower.setReadOnly(True)
        vbox_shower = QtWidgets.QVBoxLayout()
        vbox_shower.addWidget(label_shower)
        vbox_shower.addSpacing(5)
        vbox_shower.addWidget(self.shower)

        label_editor = QtWidgets.QLabel("Modifiers:")
        self.editor = QtWidgets.QTextEdit(self)
        self.editor.setFocus()
        vbox_editor = QtWidgets.QVBoxLayout()
        vbox_editor.addWidget(label_editor)
        vbox_editor.addSpacing(5)
        vbox_editor.addWidget(self.editor)        

        text_layout = QtWidgets.QGridLayout()
        text_layout.setVerticalSpacing(10)
        text_layout.setHorizontalSpacing(5)
        text_layout.addLayout(vbox_shower, 0, 0)
        text_layout.addLayout(vbox_editor, 0, 1)

        self.check_box_use = QtWidgets.QCheckBox('Use rez request modifiers')
        text_layout.addWidget(self.check_box_use, 1, 1)

        button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok |
                                                QtWidgets.QDialogButtonBox.Cancel)
        button_box.accepted.connect(self._accept_dialog)
        button_box.rejected.connect(self.reject)

        self.layout().addLayout(text_layout)
        self.layout().addSpacing(10)
        self.layout().addWidget(button_box)

    def _post_data_to_editor(self):
        self.shower.setText(self.text_packages)
        modifiers_text = ""
        for modifier in self.rez_modifiers:
            modifiers_text += modifier + "\n"
        self.editor.setText(modifiers_text)
        self.check_box_use.setChecked(self.rez_modifier_is_used)

    def _get_data_from_editor(self):
        text = self.editor.toPlainText()
        self.rez_modifiers = []
        for package in text.replace(" ", "\n").split("\n"):
            if package != "" and package not in self.rez_modifiers:
                self.rez_modifiers.append(package)
        self.rez_modifier_is_used = self.check_box_use.isChecked()

    def _accept_dialog(self):
        self._get_data_from_editor()
        self.accept()
