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

#include "cumulusproxy.h"
#include "jobtablemodel.h"
#include "jobtablewidget.h"

#include <QMessageBox>
#include <QSortFilterProxyModel>

namespace cumulus
{

JobTableWidget::JobTableWidget(QWidget* parentObject)
  : QWidget(parentObject)
  , ui(new Ui::JobTableWidget)
  , m_proxyModel(NULL)
{
  ui->setupUi(this);

  ui->table->setSortingEnabled(true);
}

JobTableWidget::~JobTableWidget()
{
  delete ui;
}

void JobTableWidget::setModel(QAbstractItemModel* model)
{
  m_proxyModel = new QSortFilterProxyModel(this);
  m_proxyModel->setSourceModel(model);
  ui->table->setModel(m_proxyModel);

  // Hide job-finished column until feature is available in cumulus
  ui->table->setColumnHidden(JobTableModel::JOB_FINISHED, true);

  // Adjust table view when contents are update
  auto* jobTableModel = dynamic_cast<JobTableModel*>(model);
  if (jobTableModel != nullptr)
  {
    QObject::connect(jobTableModel, &JobTableModel::modelUpdated, [this, model]() {
      // Resize all columns after first (job id) up to last (notes)
      int last = model->columnCount() - 1;
      for (int i = 1; i < last; ++i)
      {
        this->ui->table->resizeColumnToContents(i);
      }
    });
  }
}

void JobTableWidget::setCumulusProxy(QSharedPointer<CumulusProxy> cumulusProxy)
{
  ui->table->setCumulusProxy(cumulusProxy.get());
}

void JobTableWidget::addContextMenuAction(const QString& status, QAction* action)
{
  ui->table->addContextMenuAction(status, action);
}

} // namespace cumulus
