/**************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Installer Framework.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
**************************************************************************/
#include "packagemanagerselectlanguagepage.h"
#include "packagemanagergui.h"

#include "component.h"
#include "componentmodel.h"
#include "errors.h"
#include "fileutils.h"
#include "messageboxhandler.h"
#include "packagemanagercore.h"
#include "progresscoordinator.h"
#include "performinstallationform.h"
#include "settings.h"
#include "utils.h"
#include "scriptengine.h"
#include "productkeycheck.h"

#include "kdsysinfo.h"

#include <QApplication>

#include <QString>
#include <QWindow>
#include <QSettings>
#include <QtCore/QDir>
#include <QtCore/QPair>
#include <QtCore/QProcess>
#include <QtCore/QTimer>
#include <QTranslator>
#include <QDir>
#include <QDirIterator>
#include <QTextCodec>
#include <QFileInfo>
#include <QStringList>
#include <QScopedPointer>

#include <QCheckBox>
#include <QDesktopServices>
#include <QFileDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QProgressBar>
#include <QPushButton>
#include <QRadioButton>
#include <QTextBrowser>
#include <QTreeView>
#include <QVBoxLayout>
#include <QShowEvent>
#include <QComboBox>

using namespace KDUpdater;
using namespace QInstaller;

namespace {
#ifdef Q_OS_WIN
#include <windows.h>
const float DEFAULT_DPI = 96.0;
float windowsDpiScale()
{
    HDC screen = GetDC( 0 );
    FLOAT dpiX = static_cast<FLOAT>( GetDeviceCaps( screen, LOGPIXELSX ) );
    ReleaseDC( 0, screen );
    return dpiX / DEFAULT_DPI;
}
#endif //Q_OS_WIN
}

/*!
    \fn IntroductionPage::packageManagerCoreTypeChanged()

    This signal is emitted when the package manager core type changes.
*/

/*!
    Constructs an introduction page with \a core as parent.
*/
SelectLanguagePage::SelectLanguagePage(PackageManagerCore *core)
    : PackageManagerPage(core)
    , m_msgLabel(Q_NULLPTR)
    , m_langComboBox(Q_NULLPTR)
{
    Q_ASSERT(packageManagerCore()->isInstaller());

    setObjectName(QLatin1String("SelectLanguagePage"));

    QGridLayout *layout = new QGridLayout(this);
    setLayout(layout);

    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);

    m_msgLabel = new QLabel(this);
    m_msgLabel->setWordWrap(true);
    m_msgLabel->setObjectName(QLatin1String("MessageLabel"));
    //m_msgLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    m_langComboBox = new QComboBox(this);
    m_langComboBox->setObjectName(QLatin1String("LanguageComboBox"));
#ifdef Q_OS_OSX
    m_langComboBox->setMinimumWidth(200);
#endif
    //m_langComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    //m_langComboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

#ifdef Q_OS_WIN
    layout->addItem(new QSpacerItem(10, 15, QSizePolicy::Expanding, QSizePolicy::Expanding), 0, 1);
    layout->addWidget(m_msgLabel, 1, 1);
    layout->addItem(new QSpacerItem(10, 15, QSizePolicy::Fixed, QSizePolicy::Fixed), 2, 1);
    layout->addWidget(m_langComboBox, 3, 1);
    layout->addItem(new QSpacerItem(5, 5, QSizePolicy::Expanding, QSizePolicy::Expanding), 4, 1);

    layout->addItem(new QSpacerItem(10, 10, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 0, 1, 1);
    layout->addItem(new QSpacerItem(10, 10, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 2, 2, 1);
#elif defined Q_OS_OSX
    layout->addItem(new QSpacerItem(10, 15, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 1);
    layout->addWidget(m_msgLabel, 1, 1);
    layout->addItem(new QSpacerItem(10, 15, QSizePolicy::Fixed, QSizePolicy::Fixed), 2, 1);
    layout->addWidget(m_langComboBox, 3, 1);
    layout->addItem(new QSpacerItem(5, 5, QSizePolicy::Fixed, QSizePolicy::Expanding), 4, 1);

    layout->addItem(new QSpacerItem(80, 10, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 0, 1, 1);
    layout->addItem(new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed), 1, 2, 2, 1);

#endif

    retranslateUi();
}

void SelectLanguagePage::retranslateUi() {
    if (gui()) {
        setWindowTitle(tr("Select Setup Language"));
    }

    m_msgLabel->setText(tr("Select a language:"));
    setButtonText(QWizard::BackButton, tr("Cancel"));
    setButtonText(QWizard::NextButton, tr("Continue"));
}

bool SelectLanguagePage::validatePage()
{
    Q_ASSERT(packageManagerCore()->isInstaller());

    return true;
}

void SelectLanguagePage::entering()
{
    Q_ASSERT(packageManagerCore()->isInstaller());   

    setComplete(true);  

    if (gui()) {
        // Use a hack
        gui()->setWizardStyle(QWizard::NStyles);

        setPixmap(QWizard::WatermarkPixmap, QPixmap());
        setPixmap(QWizard::LogoPixmap, QPixmap());
        setPixmap(QWizard::BackgroundPixmap, QPixmap());
        setPixmap(QWizard::BannerPixmap, QPixmap());

        gui()->setOption(QWizard::IgnoreSubTitles, true);

#ifdef Q_OS_OSX
        gui()->setOption(QWizard::NoBackButtonOnStartPage, false);

        gui()->button(QWizard::BackButton)->setEnabled(true);
        gui()->button(QWizard::BackButton)->disconnect();
        connect(gui()->button(QWizard::BackButton), &QAbstractButton::clicked,
                [&](){
            gui()->cancelButtonClicked();
        });
#endif

        m_langComboBox->disconnect();
        m_langComboBox->clear();

        for (const QString &lang : gui()->availableLanguages())
            m_langComboBox->addItem(lang);

        connect(m_langComboBox, SIGNAL(currentIndexChanged(int)),
                this, SLOT(onCurrentIndexChanged(int)));

        int index = m_langComboBox->findText(gui()->currentLanguage());
        if ( index != -1 ) { // -1 for not found
           m_langComboBox->setCurrentIndex(index);
        }
    }

#ifdef Q_OS_WIN
    // Scale with fixed size
    wizard()->setFixedSize( windowsDpiScale() * 300.0f,
                            windowsDpiScale() * 180.0f );
#elif defined Q_OS_OSX
    wizard()->setFixedSize( 450.0f,
                            220.0f);
#endif

    gui()->moveToCenterOfTheScreen();
}

void SelectLanguagePage::leaving()
{
    Q_ASSERT(packageManagerCore()->isInstaller());

#ifdef Q_OS_OSX
    gui()->setOption(QWizard::NoBackButtonOnStartPage, true);
#endif
    // Restore max and min sizes for WIZARD, not for page
    if (packageManagerCore()->settings().wizardMaximumWidth() > 0)
        wizard()->setMaximumWidth(packageManagerCore()->settings().wizardMaximumWidth());
    else
        wizard()->setMaximumWidth(65535); // Always define max size, because we use set fixed size before

    if (packageManagerCore()->settings().wizardMaximumHeight() > 0)
        wizard()->setMaximumHeight(packageManagerCore()->settings().wizardMaximumHeight());
    else
        wizard()->setMaximumHeight(65535); // Always define max size, because we use set fixed size before

    if (packageManagerCore()->settings().wizardDefaultWidth() > 0)
        wizard()->setMinimumWidth(packageManagerCore()->settings().wizardDefaultWidth());
    if (packageManagerCore()->settings().wizardDefaultHeight() > 0)
        wizard()->setMinimumHeight(packageManagerCore()->settings().wizardDefaultHeight());

    // Restore wizard style
    wizard()->setWizardStyle(gui()->getStyle(packageManagerCore()->settings().wizardStyle()));

    // Restore screen position
    gui()->moveToCenterOfTheScreen();
}

void SelectLanguagePage::onCurrentIndexChanged(int index) {
    Q_UNUSED(index);
    Q_ASSERT(packageManagerCore()->isInstaller());

    if (gui())
        gui()->setCurrentLanguage(m_langComboBox->currentText());
}
