from PySide2.QtWidgets import QDialog, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout,\
QLabel, QCheckBox
from PySide2.QtCore import Qt
from PySide2.QtGui import QIntValidator

class PropertiesWindow(QDialog):
    def __init__(self, operation, main_window):
        super(PropertiesWindow, self).__init__()
        self.operation = operation
        self._window = main_window
        self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowCloseButtonHint)
        self.setWindowTitle("Properties")

        self.name_layout = QHBoxLayout()
        self.name_layout.setSpacing(50)
        self.name_label = QLabel("Name:")
        self.edit_name = QLineEdit(self.operation.operation_path_name)
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.edit_name)

        self.vertical_layout = QVBoxLayout()
        self.vertical_layout.addLayout(self.name_layout)

        if self.operation.operation_path_name == "c":
            self.constant_layout = QHBoxLayout()
            self.constant_layout.setSpacing(50)
            self.constant_value = QLabel("Constant:")
            self.edit_constant = QLineEdit(str(self.operation.operation.value))
            self.only_accept_int = QIntValidator()
            self.edit_constant.setValidator(self.only_accept_int)
            self.constant_layout.addWidget(self.constant_value)
            self.constant_layout.addWidget(self.edit_constant)
            self.vertical_layout.addLayout(self.constant_layout)

        self.show_name_layout = QHBoxLayout()
        self.check_show_name = QCheckBox("Show name?")
        if self.operation.is_show_name:
            self.check_show_name.setChecked(1)
        else:
            self.check_show_name.setChecked(0)
        self.check_show_name.setLayoutDirection(Qt.RightToLeft)
        self.check_show_name.setStyleSheet("spacing: 170px")
        self.show_name_layout.addWidget(self.check_show_name)
        self.vertical_layout.addLayout(self.show_name_layout)

        self.ok = QPushButton("OK")
        self.ok.clicked.connect(self.save_properties)
        self.vertical_layout.addWidget(self.ok)
        self.setLayout(self.vertical_layout)

    def save_properties(self):
        self._window.logger.info(f"Saving properties of operation: {self.operation.name}.")
        self.operation.name = self.edit_name.text()
        self.operation.label.setPlainText(self.operation.name)
        if self.operation.operation_path_name == "c":
            self.operation.operation.value = self.edit_constant.text()
        if self.check_show_name.isChecked():
            self.operation.label.setOpacity(1)
            self.operation.is_show_name = True
        else:
            self.operation.label.setOpacity(0)
            self.operation.is_show_name = False
        self.reject()