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


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

        self.file_names = []

        self.ui5 = uic.loadUi("UI_FILES/CodeGeneratorDialogWindow.ui", self)
        self.ui5.setWindowTitle("Generate Code")
        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
        
        # Initialize everything
        self.load_user_input()

    @lrm_slot
    def load_user_input(self):
        # Connect the import json button to a function that handles reading and importing json.
        self.import_json_button.clicked.connect(self.open_json_screen_definition_file_dialog)

        # Connect the save as button to a function that handles specifying the output python file name.
        self.save_as_button.clicked.connect(self.save_as)
        
        # Connect te "OK" button to the function that will be responsible for calling everything for generating code.
        self.ui5.buttonBox.accepted.connect(self.generate_and_save_code)

    @lrm_slot
    def generate_and_save_code(self):
        if len(self.file_names) == 2:

            # This line of code will close the dialog window then a user presses ok.
            python_data = ScreenProcessor(self.json_screen_file_name, self.save_as_file_name)
            python_data = python_data.generate_python_string()

            with open(self.save_as_file_name, "w") as file:
                file.write(python_data)

            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_json_screen_definition_file_dialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        self.json_screen_file_name, _ = QFileDialog.getOpenFileName(self.parent, "Select screen definition", "", "JSON Files (*.json);;All Files (*)", options=options)
        if self.json_screen_file_name:
            self.import_json_button.setText(self.json_screen_file_name.split('/')[-1])
            self.file_names.append(self.json_screen_file_name)

    @lrm_slot
    def save_as(self):
        self.save_as_file_name, _ = QFileDialog.getSaveFileName(self, "Save File", "", "Python Files (*.py)")
        if self.save_as_file_name:
            self.save_as_button.setText(self.save_as_file_name.split('/')[-1])
            self.file_names.append(self.save_as_file_name)
