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

import  os;             os.system('clear')
from    datetime        import  date, datetime
import  asyncio
from    ex14_gui        import  GUI

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

class Controller:

    def __init__(self):
        self.counter = 0
        self.gui     = None


    # asyncio initialisation of Controller
    async def run(self):
        try:
            async with asyncio.TaskGroup() as tg:
                self.gui = GUI(self, tg)                # first argument is owner
                tg.create_task(self.task())
        except* Exception as exc:
            print(exc.exceptions)
            print('taskgroup terminated')


    # interpret incoming commands
    def doCommand(self, d):
        for k, v in d.items():
            if k == 'btn_click':
                now = datetime.now()
                if   v == 'Date'  : msg = f'The date of today is {date.today()}'
                elif v == 'Hour'  : msg = f'The current hour is: {now.hour}'
                elif v == 'Minute': msg = f'The current minute is: {now.minute}'
                elif v == 'Second': msg = f'The current second is: {now.second}'
                else              : msg = f'The Counter value is: {self.counter}'
                self.gui.doCommand(dict(msg=msg))


    # controller task, increments counter @ 10 Hz
    async def task(self):
        while True:
            self.counter += 1
            await asyncio.sleep(0.1)

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

try:        
    asyncio.run(Controller().run())
except KeyboardInterrupt:
    print ('\nTerminated, ctrl-c pressed')

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