"""
pyside6-rcc resources.qrc -o resources.py

"""
import sys
import logging
import argparse
import platform

from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QSettings
from PySide6.QtGui import QIcon, QPalette

from fixtracks import info, mainwindow

logging.basicConfig(level=logging.INFO, force=True)


def is_dark_mode(app: QApplication) -> bool:
    palette = app.palette()
    # Check the brightness of the window text and base colors
    text_color = palette.color(QPalette.ColorRole.WindowText)
    base_color = palette.color(QPalette.ColorRole.Base)

    # Calculate brightness (0 for dark, 255 for bright)
    def brightness(color):
        return (color.red() * 299 + color.green() * 587 + color.blue() * 114) // 1000

    return brightness(base_color) < brightness(text_color)

def set_logging(loglevel):
    logging.basicConfig(level=loglevel, force=True)

def main(args):
    set_logging(logging.DEBUG)
    if platform.system() == "Windows":
        # from PySide6.QtWinExtras import QtWin
        myappid = f"{info.organization_name}.{info.application_version}"
        # QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
    settings = QSettings()
    width = int(settings.value("app/width", 1024))
    height = int(settings.value("app/height", 768))
    x = int(settings.value("app/pos_x", 100))
    y = int(settings.value("app/pos_y", 100))

    app = QApplication(sys.argv)
    app.setApplicationName(info.application_name)
    app.setApplicationVersion(str(info.application_version))
    app.setOrganizationDomain(info.organization_name)

    # if platform.system() == 'Linux':
    # icn = QIcon(":/icons/app_icon")
    # app.setWindowIcon(icn)
    # Create a Qt widget, which will be our window.
    window = mainwindow.MainWindow(is_dark_mode(app))
    window.setGeometry(100, 100, 1024, 768)
    window.setWindowTitle("FixTracks")
    window.setMinimumWidth(1024)
    window.setMinimumHeight(768)
    window.resize(width, height)
    window.move(x, y)
    window.show()

    # Start the event loop.
    app.exec()
    pos = window.pos()
    settings.setValue("app/width", window.width())
    settings.setValue("app/height", window.height())
    settings.setValue("app/pos_x", pos.x())
    settings.setValue("app/pos_y", pos.y())


if __name__ == "__main__":
    levels = {"critical": logging.CRITICAL, "error": logging.ERROR, "warning":logging.WARNING, "info":logging.INFO, "debug":logging.DEBUG}
    parser = argparse.ArgumentParser(description="FixTracks. Tools for fixing animal tracking")
    parser.add_argument("-ll", "--loglevel", type=str, default="INFO", help=f"The log level that should be used. Valid levels are {[str(k) for k in levels.keys()]}")
    args = parser.parse_args()
    args.loglevel = levels[args.loglevel if args.loglevel.lower() in levels else "info"]

    main(args)