# CPy - Gui controller for demo form switching
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-04-16  Initial release

import  os, sys;            os.system('clear')
from    PySide6.QtWidgets   import  QApplication, QVBoxLayout, QStackedWidget, QWidget
from    ex12_form_menu      import  FormMenu
from    ex12_form_1         import  Form1
from    ex12_form_2         import  Form2

# ================================== GUI =========================================

# Global GUI controller class
class GUI(QWidget):

    # Configuring window with forms
    def __init__(self, owner):
        self.owner = owner
        self.app   = QApplication()
        super().__init__()
        self.resize(600, 400)                              # Window
        self.setWindowTitle('Qt minimal forms template')

        self.sw = QStackedWidget()                          # Forms to display
        self.sw.addWidget(FormMenu(self))
        self.sw.addWidget(Form1   (self))
        self.sw.addWidget(Form2   (self))

        lo_main = QVBoxLayout(self)                         # Main layout for forms
        lo_main.setContentsMargins(0, 0, 0, 0)
        lo_main.addWidget(self.sw)

        self.show()


    # Interpret button onClick events
    def onBtnClick(self):
        self.owner.doCommand(dict(button=self.sender().objectName()))


    # Interpret commands from owner = controller
    def doCommand(self, d):
        for k, v in d.items():
            if k == 'button':
                if   v == ''   : self.sw.setCurrentIndex(0)
                elif v == 'f1' : self.sw.setCurrentIndex(1)
                elif v == 'f2' : self.sw.setCurrentIndex(2)

# ========================== Controller =======================

# Global controller class
class Controller:

    # Instantiate required objects
    def __init__(self):
        self.gui = GUI(self)                # argument is owner
        sys.exit(self.gui.app.exec())


    # Interpret GUI events, echo it back
    def doCommand(self, d):
        if type(d) == dict:
            for k, v in d.items():
                if k == 'button': self.gui.doCommand(d)     # echo to GUI

# ============================ Main ============================

try:
    Controller()
except KeyboardInterrupt:
    print("\nTerminated, Ctrl-C pressed")
except BaseException as exc:
    print("\nUnhandled exception :", type(exc), exc)

# ================================= End ======================================
