#!/usr/bin/env python3

import os
import sys

from PySide6.QtCore import QThread
from PySide6.QtWidgets import QApplication

from load_controller.gui import GUI
from load_controller.load import Load
from load_controller.logger import Logger
from load_controller.profile_handler import ProfileHandler
from load_controller.temperatures import Temperatures
from load_controller.bms import BMSEvalBoard


def main(argv: list[str]) -> int:
    app = QApplication(sys.argv)
    profile_handler = ProfileHandler()

    load = Load(argv[1], profile_handler)
    temps = Temperatures(argv[2])
    temp_thread = QThread()
    temps.moveToThread(temp_thread)
    temp_thread.started.connect(temps.run)
    temp_thread.start()
    bms = BMSEvalBoard(argv[3], temps.temperaturesUpdated, load)
    bms_thread = QThread()
    bms.moveToThread(bms_thread)
    bms_thread.started.connect(bms.do_work)
    bms_thread.start()

    logger = Logger(bms.dataUpdated, profile_handler.currentChanged)
    gui = GUI(profile_handler, bms.dataUpdated)

    return app.exec()


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print(f"Usage: {sys.argv[0]} LOAD-PORT TEMP-PORT BMS-PORT", file=sys.stderr)
        sys.exit(os.EX_USAGE)

    sys.exit(main(sys.argv))
