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

#include "smtk/newt/qtNewtFileBrowserWidget.h"

#include <QAbstractButton>
#include <QDebug>
#include <QDialogButtonBox>
#include <QKeyEvent>
#include <QMargins>
#include <QPushButton>
#include <QVBoxLayout>

namespace newt
{

qtNewtFileBrowserDialog::qtNewtFileBrowserDialog(QWidget* parentWidget)
  : QDialog(parentWidget)
{
  QVBoxLayout* layout = new QVBoxLayout(this);
  QMargins margins = layout->contentsMargins();
  margins.setTop(0);
  layout->setContentsMargins(margins);

  m_widget = new qtNewtFileBrowserWidget(this);
  layout->addWidget(m_widget);

  layout->addSpacing(8);
  m_buttonBox =
    new QDialogButtonBox(QDialogButtonBox::Apply | QDialogButtonBox::Close, parentWidget);
  layout->addWidget(m_buttonBox);

  this->setLayout(layout);
  this->setWindowTitle("NERSC File System");
  this->resize(640, 480);

  // Connect signals
  QObject::connect(m_buttonBox, &QDialogButtonBox::clicked, [this](QAbstractButton* button) {
    auto buttonRole = this->m_buttonBox->buttonRole(button);
    if (buttonRole == QDialogButtonBox::ApplyRole)
    {
      QString path = this->m_widget->currentPath();
      emit this->applyPath(path);
    }
    else if (buttonRole == QDialogButtonBox::RejectRole)
    {
      this->reject();
    }
    else
    {
      qWarning() << "Unexpected button role" << buttonRole;
    }
  });

  // Start with Apply button disabled
  QPushButton* applyButton = m_buttonBox->button(QDialogButtonBox::Apply);
  applyButton->setEnabled(false);
  QObject::connect(m_widget, &qtNewtFileBrowserWidget::endGotoPath, [this]() {
    // Enable Apply button once the widget has traversed into NERSC file system
    this->m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
    QObject::disconnect(this->m_widget, &qtNewtFileBrowserWidget::endGotoPath, nullptr, nullptr);
  });

  // Also expose the widget's pathCopied signal
  QObject::connect(
    m_widget, &qtNewtFileBrowserWidget::pathCopied, this, &qtNewtFileBrowserDialog::pathCopied);
}

void qtNewtFileBrowserDialog::hideApplyButton()
{
  m_buttonBox->button(QDialogButtonBox::Apply)->hide();
}

void qtNewtFileBrowserDialog::keyPressEvent(QKeyEvent* keyEvent)
{
  // Prevent <Enter> key from closing the dialog
  if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return)
  {
    return;
  }

  // (else)
  QDialog::keyPressEvent(keyEvent);
}

} // namespace newt
