//=========================================================================
//  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 "qtModeSelectDialog.h"
#include "smtk/simulation/ace3p/qt/ui_qtModeSelectDialog.h"

#include <QDialogButtonBox>
#include <QListWidget>
#include <QPushButton>

namespace smtk
{
namespace simulation
{
namespace ace3p
{
qtModeSelectDialog::qtModeSelectDialog(QWidget* parentWidget)
  : QDialog(parentWidget)
  , ui(new Ui::qtModeSelectDialog)
{
  // initialize the UI
  this->ui->setupUi(this);

  // disable ok button when no modes are selected
  this->ui->m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);

  // check for selection changes to activate OK button
  QObject::connect(
    this->ui->m_list,
    &QListWidget::itemSelectionChanged,
    this,
    &qtModeSelectDialog::checkSelection);
}

void qtModeSelectDialog::checkSelection()
{
  auto selected = this->ui->m_list->selectedItems();
  bool enabled = selected.count() > 0;
  this->ui->m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enabled);
}

void qtModeSelectDialog::setJobDir(const QString& jobDir)
{
  this->m_jobDir = jobDir;
}

void qtModeSelectDialog::initTable(const QStringList& modeFiles)
{
  this->ui->m_list->clear();
  for (auto mode : modeFiles)
  {
    QListWidgetItem* item = new QListWidgetItem;

    const QString modeName = mode.split("/").last();

    item->setData(Qt::UserRole, mode);
    item->setText(modeName);

    this->ui->m_list->addItem(item);
  }
}

void qtModeSelectDialog::accept()
{
  auto selected = this->ui->m_list->selectedItems();
  QStringList selectedModes;
  for (auto item : selected)
  {
    selectedModes.push_back(item->data(Qt::UserRole).toString());
  }
  emit selectedModeFiles(m_jobDir, selectedModes);
  QDialog::accept();
}

} // namespace ace3p
} // namespace simulation
} // namespace smtk
