import sys, asyncio
import yaml
from PySide6 import QtWidgets, QtCore
from qasync import QEventLoop
from aiomqtt import Message

from pybrotlib.transport import MQTTTransport
from BROTgui.mainwindow import MainWindow


class MyTransport(MQTTTransport, QtCore.QObject):
    logMessageReceived = QtCore.Signal(str, str)

    def __init__(self, host: str, port: int):
        QtCore.QObject.__init__(self)
        MQTTTransport.__init__(self, host, port)

    async def _process_log(self, msg: Message) -> None:
        payload = str(msg.payload)[2:-2].split(' message="')
        log_message = payload[1]
        log_level = payload[0].split("level=")[1]
        self.logMessageReceived.emit(log_level, log_message)


async def main_async():
    try:
        with open("config.yml", "r") as file:
            config = yaml.safe_load(file)
        HOSTNAME = config["mqtt"]["host"]
        PORT = config["mqtt"]["port"]
        LOCATION = config["telescope"]["location"]
    except:
        print("No config.yml could be found or read.")
        print("Please provide a working config!")
        exit()

    mqtt = MyTransport(HOSTNAME, PORT)
    w = MainWindow(
        mqtt, LOCATION, telescope_name=config["telescope"]["name"], pointing_model=config["telescope"]["pointing"]
    )
    w.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
    w.show()

    loop = asyncio.get_running_loop()
    done = loop.create_future()

    # Complete the future when the window is destroyed
    w.destroyed.connect(lambda: (not done.done()) and done.set_result(None))
    await done


def main():
    app = QtWidgets.QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # avoid Qt stopping the loop first

    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    with loop:
        loop.run_until_complete(main_async())

    # Now quit Qt after main has finished
    app.quit()


if __name__ == "__main__":
    main()
