import sys
import logging

from PySide6.QtWidgets import QMessageBox, QApplication

from app.ui.view import KeyboardView

from app.utils import setup_logger

class KeyboardApplication():
    def __init__(self):
        setup_logger()
        self.logger = logging.getLogger(__name__)
        self.logger.info("Starting")

        self.qt_app = QApplication([])

        self.view = KeyboardView()

    def exit_with_error(self, error: str, additional_text: str = ""):
        self.show_error(error, additional_text)
        self.qt_app.quit()
        sys.exit(1)

    def run(self) -> int:
        self.view.show()
        status = self.qt_app.exec()
        self.cleanup()
        self.logger.info("Exiting")
        return status

    def show_error(self, text: str, detail_text: str = ""):
        error_dialog = QMessageBox()
        error_dialog.setIcon(QMessageBox.Icon.Critical)
        error_dialog.setWindowTitle("Error")
        error_dialog.setText(text)
        if detail_text:
            error_dialog.setInformativeText(detail_text)
        error_dialog.setStandardButtons(QMessageBox.StandardButton.Ok)
        error_dialog.exec()

    def cleanup(self) -> None:
        self.logger.info("Cleaning up")
        self.qt_app.quit()