//=========================================================================
//  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 "smtk/newt/qtApplicationLoginSupport.h"
#include "smtk/newt/qtNewtFileBrowserDialog.h"
#include "smtk/newt/qtNewtInterface.h"
#include "smtk/newt/qtNewtLoginDialog.h"

#include <QApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QDebug>
#include <QDialog>
#include <QSslSocket>
#include <QStringList>

int main(int argc, char* argv[])
{
  QApplication app(argc, argv);

  newt::qtApplicationLoginSupport support;
  if (!support.checkSSL())
  {
    return -1;
  }

  // Include command-line option for backdoor mock login
  QCommandLineParser parser;
  parser.addHelpOption();

  QCommandLineOption userOption(
    QStringList() << "u"
                  << "user",
    "User name for mock login",
    "user");
  parser.addOption(userOption);

  QCommandLineOption idOption(
    QStringList() << "n"
                  << "newt session id",
    "NEWT session id",
    "newtSessionid for mock login");
  parser.addOption(idOption);

  parser.process(app);

  // Display the file browser
  newt::qtNewtFileBrowserDialog* browser = new newt::qtNewtFileBrowserDialog();
  browser->hideApplyButton();
  browser->setEnabled(false);
  browser->show();

  // Login either via mock/backdoor or dialog
  if (parser.isSet(userOption) && parser.isSet(idOption))
  {
    QString user = parser.value(userOption);
    QString newtSessionId = parser.value(idOption);
    newt::qtNewtInterface::instance()->mockLogin(user, newtSessionId);
    browser->setEnabled(true);
  }
  else
  {
    // Initialize the login dialog
    newt::qtNewtLoginDialog loginDialog;
    QObject::connect(
      &loginDialog,
      &newt::qtNewtLoginDialog::entered,
      &support,
      &newt::qtApplicationLoginSupport::onCredentials);
    QObject::connect(&support, &newt::qtApplicationLoginSupport::loginComplete, [browser](bool ok) {
      if (ok)
      {
        browser->setEnabled(true);
      }
      else
      {
        qDebug() << "Login failed";
        browser->close();
        return;
      }
    });

    // Run the login dialog
    int result = loginDialog.exec();
    if (result == QDialog::DialogCode::Rejected)
    {
      browser->close();
      return -1;
    }
  }

  int retval = app.exec();
  return retval;
}
