/****************************************************************************
**
** Copyright (C) 2012 - 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "nxtqtversionfactory.h"

#include <nxtconstants.h>
#include <qtc/nxtqtversion.h>
#include <qtc/nxtsdk.h>
#include <qtc/nxtsdkmanager.h>

#include <utils/qtcassert.h>

#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>

using namespace QtSupport;
using namespace Utils;

namespace Nxt {
namespace Internal {

NxtQtVersionFactory::NxtQtVersionFactory(QObject *parent)
    : QtVersionFactory(parent)
{
}

NxtQtVersionFactory::~NxtQtVersionFactory()
{
}

bool NxtQtVersionFactory::canRestore(const QString &type)
{
    return type == QLatin1String(Constants::NXT_QT);
}

BaseQtVersion *NxtQtVersionFactory::restore(const QString &type,
                                            const QVariantMap &data)
{
    QTC_ASSERT(canRestore(type), return nullptr);
    NxtQtVersion *v = new NxtQtVersion();
    v->fromMap(data);

    // Check if the qtVersion is still valid
    QFileInfo fi = v->qmakeCommand().toFileInfo();
    if (!fi.exists() || v->virtualMachineName().isEmpty() || v->targetName().isEmpty()) {
        delete v;
        return nullptr;
    }

    return v;
}

int NxtQtVersionFactory::priority() const
{
    return 50;
}

BaseQtVersion *NxtQtVersionFactory::create(const FileName &qmakeCommand,
                                           ProFileEvaluator * /*evaluator*/,
                                           bool isAutoDetected,
                                           const QString &autoDetectionSource)
{
    const QFileInfo fi = qmakeCommand.toFileInfo();
    if (!fi.exists() || !fi.isExecutable() || !fi.isFile())
        return nullptr;

    // Check for the location of qmake
    bool found = qmakeCommand.toString().contains(NxtSdkManager::globalSdkToolsDirectory());
    if (!found)
        found = qmakeCommand.toString().contains(NxtSdkManager::sdkToolsDirectory());
    if (!found)
        return nullptr;
    return new NxtQtVersion(qmakeCommand, isAutoDetected, autoDetectionSource);
}

} // namespace Internal
} // namespace Nxt

