#include "OnboardingQmlDialog.h"

#include "LoginController.h"
#include "MegaApplication.h"
#include "Platform.h"

#include <QEvent>
#include <QScreen>

OnboardingQmlDialog::OnboardingQmlDialog(QWindow *parent)
    : QmlDialog(parent)
    , mLoggingIn(false)
    , mCloseClicked(false)
    , mForceClose(false)
    , mCreatingAccount(false)
{
}

bool OnboardingQmlDialog::getCreatingAccount() const
{
    return mCreatingAccount;
}

void OnboardingQmlDialog::setCreatingAccount(bool value)
{
    if(mCreatingAccount != value)
    {
        mCreatingAccount = value;
        emit creatingAccountChanged();
    }
}

bool OnboardingQmlDialog::getLoggingIn() const
{
    return mLoggingIn;
}

void OnboardingQmlDialog::setLoggingIn(bool value)
{
    if(mLoggingIn != value)
    {
        mLoggingIn = value;
        emit loggingInChanged();
    }
}

void OnboardingQmlDialog::forceClose()
{
    mForceClose = true;
    if(!close())
    {
        hide();
    }
}

void OnboardingQmlDialog::raise()
{
    // The following four lines are required by Ubuntu to bring the window to the front and
    // move it to the center of the current screen, if the screen is a part of a virtual desktop or multiple screen
    // we will need add the current screen offset(topleft) to the calculated central position.
    const auto& geometry = QmlDialog::screen()->geometry();
    int xPos = geometry.x() + static_cast<int>(geometry.width() * 0.5 - width() * 0.5);
    int yPos = geometry.y() + static_cast<int>(geometry.height() * 0.5 - height() * 0.5);

    hide();
    QmlDialog::setPosition(xPos, yPos);
    show();

    // requestActivate() is required by Windows; raise() by macOS.
    // Qt5-ONLY Wayland branch: on Qt5 a client cannot activate itself (the call
    // can crash), so we request attention via alert() instead.
    // TODO Qt6: remove the Wayland branch and call requestActivate()
    // unconditionally; Qt6 activates via xdg-activation without crashing.
    if (Platform::getInstance()->isWayland())
    {
        QmlDialog::alert(0);
    }
    else
    {
        QmlDialog::requestActivate();
    }
    QmlDialog::raise();
}

bool OnboardingQmlDialog::event(QEvent* event)
{
    if (event->type() == QEvent::Close)
    {
        requestPinOnTaskbar();
    }

    if (event->type() == QEvent::WindowUnblocked && mForceClose)
    {
        close();
    }
    else if (event->type() == QEvent::Close && !mForceClose)
    {
        if (mLoggingIn)
        {
            emit closingButLoggingIn();
            event->ignore();
            return true;
        }
        else if (mCreatingAccount)
        {
            emit closingButCreatingAccount();
            event->ignore();
            return true;
        }
        else // Already logged in
        {
            MegaSyncApp->getLoginController()->processOnboardingClosed();
        }
    }

    return QmlDialog::event(event);
}

void OnboardingQmlDialog::requestPinOnTaskbar() const
{
    Platform::getInstance()->pinOnTaskbar();
}
