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

#include <nxtconstants.h>
#include <device/hardware/nxthardwaredevice.h>
#include <device/hardware/nxthardwaredevicewizard.h>
#include <qtc/nxtsdkmanager.h>
#include <connection/ssh/nxtsshkeydeploymentdialog.h>

#include <coreplugin/icore.h>
#include <ssh/sshconnection.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>

#include <QFileInfo>
#include <QIcon>
#include <QInputDialog>
#include <QMessageBox>

using namespace Core;
using namespace ProjectExplorer;
using namespace QSsh;
using namespace Utils;

namespace Nxt {
namespace Internal {

NxtDeviceFactory *NxtDeviceFactory::s_instance = nullptr;

NxtDeviceFactory *NxtDeviceFactory::instance()
{
    return s_instance;
}

NxtDeviceFactory::NxtDeviceFactory()
{
    QTC_CHECK(!s_instance);
    s_instance = this;
    setObjectName(QLatin1String("NxtDeviceFactory"));
}

NxtDeviceFactory::~NxtDeviceFactory()
{
    s_instance = 0;
}

QString NxtDeviceFactory::displayNameForId(Core::Id type) const
{
    if (type == Constants::NXT_DEVICE_TYPE)
        return tr("IDS NXT Device");
    return QString();
}

bool NxtDeviceFactory::canCreate(Core::Id type)
{
    return type == Core::Id(Constants::NXT_DEVICE_TYPE);
}

QList<Core::Id> NxtDeviceFactory::availableCreationIds() const
{
    return QList<Core::Id>() << Core::Id(Constants::NXT_DEVICE_TYPE);
}

QIcon NxtDeviceFactory::iconForId(Core::Id type) const
{
    Q_UNUSED(type);
    return QIcon();
}

IDevice::Ptr NxtDeviceFactory::create(Core::Id id) const
{
    QTC_ASSERT(id == Constants::NXT_DEVICE_TYPE, return IDevice::Ptr());

#if 0 /* ssh */
    QStringList choices = QStringList() << tr("Physical device");
    bool ok;
    QString machineType = QInputDialog::getItem(ICore::dialogParent(),
            tr("Create a IDS NXT Device"),
            tr("Add physical device?"),
            choices, 0, false, &ok);
    if (!ok)
#endif /* ssh */
    NxtHardwareDeviceWizard wizard(ICore::dialogParent());
    if (wizard.exec() != QDialog::Accepted)
        return IDevice::Ptr();

#if 0 /* ssh */
    if (machineType == choices.first()) {
        NxtHardwareDeviceWizard wizard(ICore::dialogParent());
        if (wizard.exec() != QDialog::Accepted)
            return IDevice::Ptr();

        if (wizard.isNewSshKeysRquired() && !wizard.privateKeyFilePath().isEmpty()) {

            QString privKeyPath = wizard.privateKeyFilePath();

            if (QFileInfo(privKeyPath).exists()) {
                QFile(privKeyPath).remove();
            }

            QString error;

            if (!NxtSdkManager::generateSshKey(privKeyPath, error)) {
                QMessageBox::critical(ICore::dialogParent(), tr("Could not generate key."), error);
            }
        }

        {
            SshConnectionParameters sshParams;
            sshParams.setHost(wizard.hostName());
            sshParams.setUserName(wizard.userName());
            sshParams.setPort(wizard.sshPort());
            sshParams.timeout = wizard.timeout();
            sshParams.authenticationType = SshConnectionParameters::AuthenticationTypePassword;
            sshParams.setPassword(wizard.password());
            NxtSshKeyDeploymentDialog dlg(ICore::dialogParent());
            dlg.setSShParameters(sshParams);
            dlg.setPublicKeyPath(wizard.publicKeyFilePath());
            if (dlg.exec() == QDialog::Rejected) {
                return IDevice::Ptr();
            }
        }

        SshConnectionParameters sshParams;
        //sshParams.options &= ~SshConnectionOptions(SshEnableStrictConformanceChecks); // For older SSH servers.
        sshParams.setHost(wizard.hostName());
        sshParams.setUserName(wizard.userName());
        sshParams.setPort(wizard.sshPort());
        sshParams.timeout = wizard.timeout();
        sshParams.authenticationType = SshConnectionParameters::AuthenticationTypePublicKey;
        sshParams.privateKeyFile = wizard.privateKeyFilePath();

        NxtHardwareDevice::Ptr device = NxtHardwareDevice::create(wizard.configurationName());
        device->setArchitecture(wizard.architecture());
        device->setSharedSshPath(wizard.sharedSshPath());
        device->setFreePorts(PortList::fromString(wizard.freePorts()));
        //device->setFreePorts(PortList::fromString(QLatin1String("10000-10100")));
        device->setSshParameters(sshParams);

        emit const_cast<NxtDeviceFactory *>(this)->deviceCreated(device);

        return device;
    }

    return IDevice::Ptr();
#endif /* ssh */

    // add NXT device
    // Important: connection is done via REST, not SSH. REST Credentials are stored in sshParameters()!
    {
        NxtHardwareDevice::Ptr device = NxtHardwareDevice::create(wizard.configurationName());
        auto ssh = device->sshParameters();
        ssh.setHost(wizard.hostName());
        ssh.setUserName(wizard.userName());
        ssh.setPassword(wizard.password());
        device->setSshParameters(ssh);
        device->setArchitecture(Abi::ArmArchitecture);
        emit const_cast<NxtDeviceFactory *>(this)->deviceCreated(device);
        return device;
    }
}

bool NxtDeviceFactory::canRestore(const QVariantMap &map) const
{
    return canCreate(IDevice::typeFromMap(map));
}

IDevice::Ptr NxtDeviceFactory::restore(const QVariantMap &map) const
{
    QTC_ASSERT(canRestore(map), return IDevice::Ptr());
#if 0 /* ssh */
    if (NxtDevice::workaround_machineTypeFromMap(map) == IDevice::Hardware) {
#endif /* ssh */
        const IDevice::Ptr device = NxtHardwareDevice::create();
        device->fromMap(map);
        return device;
#if 0 /* ssh */
    }
#endif /* ssh */
}

} // namespace Internal
} // namespace Nxt
