#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QLayout>
#include <QWindow>
#include <QDebug>
#include <QGridLayout>
#include <QScreen>
#include <QGuiApplication>

#include "LanguageManager.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 启用触摸事件
    // setAttribute(Qt::WA_AcceptTouchEvents);
    setAttribute(Qt::WA_AcceptTouchEvents, true);
    ui->stackedWidget->setAttribute(Qt::WA_AcceptTouchEvents, true);

    // this->installEventFilter(this);
    QScreen *screen = QGuiApplication::primaryScreen();
    if (screen) {
        QRect screenGeometry = screen->geometry();
        ui->stackedWidget->setMaximumSize(screenGeometry.width(), screenGeometry.height());
    }
}

void MainWindow::activate()
{
    if (QWindow *window = this->windowHandle()) {
        window->requestActivate();
    } else {
        this->showNormal();
        this->activateWindow();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
    initWidget();
    initConnect();
}

void MainWindow::initWidget()
{
    m_startup = new FormStartUp();
    ui->stackedWidget->addWidget(m_startup);

    m_home = new FormHome();
    m_home->init();
    ui->stackedWidget->addWidget(m_home);

    // 强制布局系统更新
    ui->stackedWidget->updateGeometry();

    ui->stackedWidget->setCurrentWidget(m_startup);

    if (QGuiApplication::platformName().contains("wayland")) {
        setWindowFlags(windowFlags() |
                       Qt::FramelessWindowHint |
                       Qt::WindowStaysOnTopHint |
                       Qt::BypassWindowManagerHint);
    }
}

void MainWindow::initConnect()
{
    connect(m_startup,  &FormStartUp::screenSaverHide,  this, [this]() {
        ui->stackedWidget->setCurrentWidget(m_home);
    });
    connect(m_home,     &FormHome::userInactive,        this, [this]() {
        ui->stackedWidget->setCurrentWidget(m_startup);
    });

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
}

void MainWindow::showEvent(QShowEvent *event)
{
    QMainWindow::showEvent(event);

    // Wayland 环境下需要延迟激活
    if (QGuiApplication::platformName().contains("wayland")) {
        QTimer::singleShot(100, this, &MainWindow::activate);
    } else {
        this->activate();
    }
}
