from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QFileDialog, QMessageBox
from lrm.exceptions import lrm_slot


class NewScreen(QtWidgets.QDialog):
    def __init__(self, parent, display_picture) -> None:
        super().__init__()

        self.file_name = False

        self.ui2 = uic.loadUi("UI_FILES/NewScreen.ui", self)
        self.ui2.setWindowTitle("New Screen")
        self.setModal(True)
        self.show()

        # Parent is actually the main window, but there is a chain through buttons handler, combobox handler and then to main window
        self.parent = parent

        # instance of a buttons handler
        self.display_picture = display_picture
        
        # Initialize everything
        self.load_user_input()

    @lrm_slot
    def load_user_input(self):
        # Connect everything that was selected or written by the user to the OK button, so that it is saved all the time
        self.select_screenshot_button.clicked.connect(self.open_file_dialog)
        self.ui2.buttonBox.accepted.connect(self.save_user_input)

    @lrm_slot
    def save_user_input(self):
        if self.name_line_edit.text() and self.file_name:
            
            # Call the screenshot handler (but through the buttons because that's where the screenshot instance is created)
            self.display_picture(self.file_name, self.name_line_edit.text())

            # This line of code will close the dialog window then a user presses ok.
            self.accept()
        else:
            QMessageBox.warning(self, "Error", "Please fill in all the required fields.")

            # This line of code will re-open the dialog window because something was missing!
            self.show()

    @lrm_slot
    def open_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.file_name, _ = QFileDialog.getOpenFileName(self.parent,"Select Image", "","Images (*.png *.xpm *.jpg *.bmp);;All Files (*)", options=options)
        if self.file_name:
            self.select_screenshot_button.setText(self.file_name.split('/')[-1])
            self.ui2.buttonBox.accepted.disconnect()
            self.ui2.buttonBox.accepted.connect(self.save_user_input)
