import asyncio
import sys
import qasync
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtGui import QIcon
from app.controllers.main_controller import MainController
from app.core.theme import theme_manager, set_dark_title_bar
import app.core.config as config
from app.core.database import init_db

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle(config.APP_HEADER)
        self.setMinimumSize(400, 650)

        self.controller = MainController()
        self.setCentralWidget(self.controller)
        
        theme_manager.theme_changed.connect(self.apply_theme)
        self.apply_theme(theme_manager.get_theme())

    def apply_theme(self, theme):
        is_dark = theme == "dark"
        if is_dark:
            self.setStyleSheet("background-color: #2e2e2e;")
        else:
            self.setStyleSheet("background-color: #f0f0f0;")

        # получаем HWND и красим системный бар
        hwnd = int(self.winId())
        try:
            set_dark_title_bar(hwnd, is_dark)
        except Exception as e:
            print("Не удалось поменять цвет системного бара:", e)

async def main():
    init_db()
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon("app/icons/logo3.png"))
    
    loop = qasync.QEventLoop(app)
    asyncio.set_event_loop(loop)

    window = MainWindow()
    window.show()
    
    await loop.run_forever()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        sys.exit(0)
