/**************************************************************************
**
** 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 "packagemanagerlicenceagreementpage.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 <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>

#ifdef Q_OS_WIN
# include <qt_windows.h>
# include <QWinTaskbarButton>
# include <QWinTaskbarProgress>
#endif

using namespace KDUpdater;
using namespace QInstaller;

// -- LicenseAgreementPage

/*!
    \class QInstaller::LicenseAgreementPage
    \inmodule QtInstallerFramework
    \brief The LicenseAgreementPage presents a license agreement to the end
    users for acceptance.

    The license check page is displayed if you specify a license file in the
    package information file and copy the file to the meta directory. End users must
    accept the terms of the license agreement for the installation to continue.
*/

/*!
    Constructs a license check page with \a core as parent.
*/
LicenseAgreementPage::LicenseAgreementPage(PackageManagerCore *core)
    : PackageManagerPage(core)
{
    setPixmap(QWizard::WatermarkPixmap, QPixmap());
    setObjectName(QLatin1String("LicenseAgreementPage"));    

    m_licenseListWidget = new QListWidget(this);
    m_licenseListWidget->setObjectName(QLatin1String("LicenseListWidget"));
    m_licenseListWidget->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding);
    connect(m_licenseListWidget, &QListWidget::currentItemChanged,
        this, &LicenseAgreementPage::currentItemChanged);

    m_textBrowser = new QTextBrowser(this);
    m_textBrowser->setReadOnly(true);
    m_textBrowser->setOpenLinks(true);
    m_textBrowser->setOpenExternalLinks(true);
    m_textBrowser->setObjectName(QLatin1String("LicenseTextBrowser"));
    m_textBrowser->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
    connect(m_textBrowser, &QTextBrowser::anchorClicked, this, &LicenseAgreementPage::openLicenseUrl);

    QHBoxLayout *licenseBoxLayout = new QHBoxLayout();
    licenseBoxLayout->addWidget(m_licenseListWidget);
    licenseBoxLayout->addWidget(m_textBrowser);
    licenseBoxLayout->setContentsMargins(0,0,0,0);
    licenseBoxLayout->setMargin(0);

    QGridLayout *layout = new QGridLayout(this);
    setLayout(layout);
#ifdef Q_OS_WIN
    m_msgLabel = new QLabel;
   m_msgLabel->setWordWrap(true);
   m_msgLabel->setObjectName(QLatin1String("MessageLabel"));
   m_msgLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);   

   layout->addWidget(m_msgLabel, 0, 0, 1, 3);
   layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 0, 1, 3);
#elif defined Q_OS_OSX
   m_textBrowser->setFrameStyle(QFrame::NoFrame);
#endif
    layout->addLayout(licenseBoxLayout, 2, 0, 1, 3);
    layout->setContentsMargins(0,0,0,0);
    layout->setMargin(0);
}

/*!
    Initializes the page's fields based on values from fields on previous
    pages.
*/
void LicenseAgreementPage::entering()
{
    setComplete(true);

    setColoredTitle(tr("Software License Agreement"));
#ifdef Q_OS_WIN
    m_msgLabel->setText(tr("Press the down key to view the rest of the agreement"));
#endif

    m_licenseListWidget->clear();
    m_textBrowser->setHtml(QString());
    m_licenseListWidget->setVisible(false);

    packageManagerCore()->calculateComponentsToInstall();
    foreach (QInstaller::Component *component, packageManagerCore()->orderedComponentsToInstall())
        addLicenseItem(component->licenses());

    const int licenseCount = m_licenseListWidget->count();
    if (licenseCount > 0) {
        m_licenseListWidget->setVisible(licenseCount > 1);
        m_licenseListWidget->setCurrentItem(m_licenseListWidget->item(0));
    }

#if (defined Q_OS_WIN) || (defined Q_OS_OSX)
    if (packageManagerCore()->isInstaller()) {
        if (PackageManagerGui *w = gui()) {
            #ifdef Q_OS_WIN
            w->setOption(QWizard::IgnoreSubTitles, false);
            #elif defined Q_OS_OSX
            w->setOption(QWizard::IgnoreSubTitles, true);
            #endif

            // Update default actions
            w->button(QWizard::NextButton)->disconnect();
            connect(w->button(QWizard::NextButton), &QAbstractButton::clicked,
                    this, &LicenseAgreementPage::onShowModalDialog);
        }
    }
#endif

    updateUi();
}

void LicenseAgreementPage::currentItemChanged(QListWidgetItem *current)
{
    if (current) {
        QByteArray data = current->data(Qt::UserRole).toByteArray();
        QTextCodec *codec = Qt::codecForHtml(data);
        QString str = codec->toUnicode(data);

        m_textBrowser->setHtml(str);
    }
}

#if (defined Q_OS_WIN) || (defined Q_OS_OSX)
void LicenseAgreementPage::onShowModalDialog() {
    QMessageBox msgBox(MessageBoxHandler::currentBestSuitParent());
    msgBox.setWindowTitle(productName());
    msgBox.setText(tr("<b>To continue installing the software you must agree to the terms of the software license agreement</b><br><br>Click Agree to continue or click Disagree to cancel the installation and quit the installer."));
    msgBox.setWindowFlags(Qt::WindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint));
#if (defined Q_OS_OSX)
    msgBox.setWindowModality(Qt::WindowModal);
#elif defined Q_OS_WIN
#endif

    QPushButton* pButtonDisagree = msgBox.addButton(tr("Disagree"), QMessageBox::NoRole);
    QPushButton* pButtonAgree = msgBox.addButton(tr("Agree"), QMessageBox::YesRole);
    msgBox.addButton(tr("Read License"), QMessageBox::ResetRole);

    msgBox.setDefaultButton(pButtonAgree);

    msgBox.exec();

    if (msgBox.clickedButton()== pButtonAgree) {
        gui()->next();
    }
    else if (msgBox.clickedButton()== pButtonDisagree) {
        gui()->rejectWithoutPrompt();
    }
}
#endif

void LicenseAgreementPage::openLicenseUrl(const QUrl &url)
{
    QDesktopServices::openUrl(url);
}

// < display name, < file name, file content > >
void LicenseAgreementPage::addLicenseItem(const QHash<QString, QPair<QString, QByteArray> > &hash)
{    
    // Try to find license for current language
    bool licenseFound = false;
    for (QHash<QString, QPair<QString, QByteArray> >::const_iterator it = hash.begin();
        it != hash.end(); ++it) {
        if (it.value().first.contains(gui()->currentLanguageFileName(), Qt::CaseInsensitive)) {
            QListWidgetItem *item = new QListWidgetItem(it.key(), m_licenseListWidget);
            item->setData(Qt::UserRole, it.value().second);
            licenseFound = true;
        }
    }

    if (licenseFound)
        return;

    for (QHash<QString, QPair<QString, QByteArray> >::const_iterator it = hash.begin();
        it != hash.end(); ++it) {
            QListWidgetItem *item = new QListWidgetItem(it.key(), m_licenseListWidget);
            item->setData(Qt::UserRole, it.value().second);
    }
}

void LicenseAgreementPage::updateUi()
{
#ifndef Q_OS_OSX
    QString subTitleText;
    if (m_licenseListWidget->count() == 1)
        subTitleText = tr("Please read the following license agreement carefully.");
    else
        subTitleText = tr("Please read the following license agreements carefully.");

    setColoredSubTitle(subTitleText);
#endif
}
