# Introduction to Qt - demonstrating task asyncio controlled. main = ex14_main_aio.py
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-04-02  Initial release

import  asyncio
from    PySide6.QtWidgets   import  QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from    PySide6.QtCore      import  Qt

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

class GUI(QWidget):

    # Background setup of GUI
    def __init__(self, owner, tg):
        self.owner = owner
        self.tg    = tg
        self.app   = QApplication([])
        super().__init__()
        self.setWindowTitle('The Title')

        lo_main = QVBoxLayout()
        self.label = QLabel('label', self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("font-size: 20px; font-weight: bold; color: red")
        lo_main.addWidget(self.label)

        lo_buttons = QHBoxLayout()
        for caption in('Date', 'Hour', 'Minute', 'Second', 'Counter'):
            btn = QPushButton(caption)
            btn.clicked.connect(self.onBtnClick)
            lo_buttons.addWidget(btn)

        lo_main.addLayout(lo_buttons)
        self.setLayout(lo_main)

        tg.create_task(self.task())
        self.show()


    # handle buttons click, send dictionary to controller
    def onBtnClick(self):
        self.owner.doCommand(dict(btn_click=self.sender().text()))


    # interpret incoming dictionary commands
    def doCommand(self, d):
        for k, v in d.items():
            if k == 'msg': self.label.setText(v)


    # overwrite closeEvent to terminate asyncio loop
    def closeEvent(self, event):
        self.tg.cancelAll()


    # GUI task, running Qt loop @ 20 Hz
    async def task(self):
        while True:
            await asyncio.sleep(0.05)
            self.app.processEvents()
            
# ================================= Test =====================================
    
if __name__ == '__main__':

    import  os;                 os.system('clear')
    from    PySide6.QtWidgets   import  QApplication

    class Controller:

        async def run(self):
            async with asyncio.TaskGroup() as tg:
                self.gui = GUI(self, tg)                # first argument is owner


        def doCommand(self, d):
            print(d)


    asyncio.run(Controller().run())

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