//=========================================================================
//  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 "plugin/pqNerscFileBrowserPanel.h"

#include "plugin/pqNerscLoginBehavior.h"

#include "smtk/newt/qtNewtFileBrowserWidget.h"
#include "smtk/newt/qtNewtInterface.h"

#include <QDebug>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>

class pqNerscFileBrowserPanel::Internal
{
public:
  QWidget* MainWidget;
  newt::qtNewtFileBrowserWidget* BrowserWidget;
  newt::qtNewtInterface* Newt;

  Internal()
    : MainWidget(nullptr)
    , BrowserWidget(nullptr)
    , Newt(newt::qtNewtInterface::instance())
  {
  }
};

pqNerscFileBrowserPanel::pqNerscFileBrowserPanel(QWidget* parent)
  : QDockWidget(parent)
{
  this->setObjectName("NERSC File Browser");
  this->setWindowTitle("NERSC File Browser");
  m_internal = new pqNerscFileBrowserPanel::Internal;

  bool loggedIn = !m_internal->Newt->userName().isEmpty();

  // Initialize widgets
  m_internal->MainWidget = new QWidget(this);
  QVBoxLayout* layout = new QVBoxLayout;

  QPushButton* loginButton = new QPushButton("Login To NERSC");
  loginButton->setEnabled(!loggedIn);
  layout->addWidget(loginButton, 0, Qt::AlignHCenter);

  m_internal->BrowserWidget = new newt::qtNewtFileBrowserWidget(this);
  layout->addWidget(m_internal->BrowserWidget);
  m_internal->BrowserWidget->setEnabled(loggedIn);

  // Finish main widget
  m_internal->MainWidget->setLayout(layout);
  this->setWidget(m_internal->MainWidget);

  // Setup connections
  pqNerscLoginBehavior* loginBehavior = pqNerscLoginBehavior::instance();
  QObject::connect(
    loginButton, &QPushButton::clicked, loginBehavior, &pqNerscLoginBehavior::startLogin);

  QObject::connect(m_internal->Newt, &newt::qtNewtInterface::loginComplete, [this, loginButton]() {
    loginButton->setEnabled(false);
    this->m_internal->BrowserWidget->setEnabled(true);
  });
}

pqNerscFileBrowserPanel::~pqNerscFileBrowserPanel()
{
  delete m_internal;
}
