//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================

#include "qtApplicationLoginSupport.h"

#include <QDebug>
#include <QMessageBox>
#include <QNetworkReply>
#include <QSslSocket>
#include <QWidget>

namespace newt
{

qtApplicationLoginSupport::qtApplicationLoginSupport(QWidget* parentWidget)
  : QObject(parentWidget)
{
  m_newt = newt::qtNewtInterface::instance(this);
}

bool qtApplicationLoginSupport::checkSSL() const
{
  qDebug() << "sslLibraryVersionString" << QSslSocket::sslLibraryVersionString();
  if (QSslSocket::supportsSsl())
  {
    return true;
  }

  // (else)
  QMessageBox::critical(
    nullptr, "Error", "Cannot run because OpenSSL missing or is an unsupported version.");
  return false;
}

void qtApplicationLoginSupport::onCredentials(const QString& username, const QString& password)
{
  QObject::connect(m_newt, &qtNewtInterface::error, this, &qtApplicationLoginSupport::onError);
  QObject::connect(m_newt, &qtNewtInterface::loginFail, this, &qtApplicationLoginSupport::onError);
  QObject::connect(
    m_newt, &qtNewtInterface::loginComplete, [this]() { emit this->loginComplete(true); });

  m_newt->login(username, password);
}

void qtApplicationLoginSupport::onError(const QString& message)
{
  qDebug() << "ERROR:" << message;
  emit this->loginComplete(false);
}
} // namespace newt
