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

#include "plugin/pqACE3PAutoStart.h"
#include "plugin/pqACE3PJobsBehavior.h"
#include "plugin/pqACE3PSaveBehavior.h"
#include "plugin/pqACE3PStagesBehavior.h"
#include "smtk/simulation/ace3p/qt/qtProjectRuntime.h"

// SMTK
#include "smtk/extension/paraview/appcomponents/pqSMTKBehavior.h"
#include "smtk/extension/paraview/appcomponents/pqSMTKResource.h"
#include "smtk/extension/paraview/appcomponents/pqSMTKWrapper.h"
#include "smtk/io/Logger.h"
#include "smtk/project/Manager.h"
#include "smtk/project/Project.h"

// Paraview
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqCoreUtilities.h"
#include "pqObjectBuilder.h"
#include "pqProxy.h"
#include "pqServer.h"
#include "pqServerManagerModel.h"
#include "pqView.h"
#include "vtkSMViewLayoutProxy.h"

#include <QAction>
#include <QDebug>
#include <QList>
#include <QMessageBox>
#include <QtGlobal>

#include <vector>

//-----------------------------------------------------------------------------
pqACE3PCloseReaction::pqACE3PCloseReaction(QAction* parentObject)
  : Superclass(parentObject)
{
}

//-----------------------------------------------------------------------------
void pqACE3PCloseReaction::onTriggered()
{
  pqACE3PCloseBehavior::instance()->closeProject();
}

//-----------------------------------------------------------------------------
static pqACE3PCloseBehavior* g_instance = nullptr;

//-----------------------------------------------------------------------------
pqACE3PCloseBehavior::pqACE3PCloseBehavior(QObject* parent)
  : Superclass(parent)
{
}

//-----------------------------------------------------------------------------
pqACE3PCloseBehavior* pqACE3PCloseBehavior::instance(QObject* parent)
{
  if (!g_instance)
  {
    g_instance = new pqACE3PCloseBehavior(parent);
  }

  if (g_instance->parent() == nullptr && parent)
  {
    g_instance->setParent(parent);
  }

  return g_instance;
}

//-----------------------------------------------------------------------------
pqACE3PCloseBehavior::~pqACE3PCloseBehavior()
{
  if (g_instance == this)
  {
    g_instance = nullptr;
  }

  QObject::disconnect(this);
}

//-----------------------------------------------------------------------------
bool pqACE3PCloseBehavior::closeProject()
{
  // Get the builtin server and make sure that one is active
  pqServer* builtinServer = pqACE3PAutoStart::builtinServer();
  pqActiveObjects::instance().setActiveServer(builtinServer);

  // Get current project
  auto runtime = smtk::simulation::ace3p::qtProjectRuntime::instance();
  auto project = runtime->project();
  if (project == nullptr)
  {
    qWarning() << "Internal error - no active project.";
    return true;
  }

  // hide the Stages & Jobs panels when no project is active
  pqACE3PStagesBehavior::instance()->setPanelVisible(false);
  pqACE3PJobsBehavior::instance()->setPanelVisible(false);

  // Check if project is modified
  if (!project->clean())
  {
    QMessageBox msgBox;
    msgBox.setText("The project has been modified.");
    msgBox.setInformativeText("Do you want to save your changes?");
    auto buttons = QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel;
    msgBox.setStandardButtons(buttons);
    msgBox.setDefaultButton(QMessageBox::Save);

    int ret = msgBox.exec();
    if (ret == QMessageBox::Cancel)
    {
      return false;
    }
    else if (ret == QMessageBox::Save)
    {
      if (!pqACE3PSaveBehavior::instance()->saveProject())
      {
        return false;
      }
    }
  } // if (project modified)

  // Access the builtin server and get the project manager
  pqServerManagerModel* smModel = pqApplicationCore::instance()->getServerManagerModel();
  pqSMTKWrapper* wrapper = pqSMTKBehavior::instance()->resourceManagerForServer(builtinServer);
  auto projectManager = wrapper->smtkProjectManager();
  auto projectName = project->name();
  auto resManager = std::static_pointer_cast<smtk::resource::Resource>(project)->manager();

  // First mark all project resources for removal
  for (auto iter = project->resources().begin(); iter != project->resources().end(); ++iter)
  {
    auto resource = *iter;
    resource->setMarkedForRemoval(true);
  }

  // Then remove resources from resource manager
  for (auto iter = project->resources().begin(); iter != project->resources().end(); ++iter)
  {
    resManager->remove(*iter);
  }

  runtime->unsetProject(project);

  // Remove project from *both* resource manager & project manager
  resManager->remove(project);
  projectManager->remove(project);

  emit this->projectClosed();

  // Reset render views and destroy any remaining pipeline objects (job data, e.g.)
  pqCoreUtilities::processEvents();
  pqApplicationCore* core = pqApplicationCore::instance();
  pqObjectBuilder* builder = core->getObjectBuilder();

  QList<pqServer*> serverList = smModel->findItems<pqServer*>();
  foreach (pqServer* server, serverList)
  {
    // Find the layout proxy
    vtkSMViewLayoutProxy* layout = nullptr;
    QList<pqProxy*> proxyList = smModel->findItems<pqProxy*>(server);
    foreach (pqProxy* proxy, proxyList)
    {
      // qDebug() << item << typeid(item).name() << proxy->getSMName () << proxy->getSMGroup();
      vtkSMViewLayoutProxy* castLayout = dynamic_cast<vtkSMViewLayoutProxy*>(proxy->getProxy());
      if (castLayout != nullptr)
      {
        layout = castLayout;
        break;
      }
    } // foreach (proxy)

    // Future: should be able to remove this sanity check
    if (layout == nullptr)
    {
      qWarning() << "Internal error: no layout found for server";
      continue;
    }

    // Destroy all the views and collapse the layout
    QList<pqView*> viewList = smModel->findItems<pqView*>(server);
    foreach (pqView* view, viewList)
    {
#if 0
      // This code triggers a crash in ParaView for *some* projects.
      vtkSMViewProxy* viewProxy = view->getViewProxy();
      int location = layout->RemoveView(viewProxy);
      //layout->Collapse(location);
      builder->destroy(view);
#else
      // Simply destroying the view seems to be OK, however, a
      // layout Reset() is required (after the loop completes)
      // to collapse any split/multiple locations.
      builder->destroy(view);
#endif
    }
    layout->Reset(); // collapses all locations

    // Add single new view
    pqView* newView = builder->createView("RenderView", server);
    builder->addToLayout(newView);
    newView->render(); // seems to clear remnants from the deleted views

    // Destroy any remaining pipeline sources
    QList<pqPipelineSource*> sourceList = smModel->findItems<pqPipelineSource*>(server);
    foreach (pqPipelineSource* source, sourceList)
    {
      builder->destroy(source);
    }

#ifndef NDEBUG
    // Report what's left
    proxyList = smModel->findItems<pqProxy*>(server);
    foreach (pqProxy* proxy, proxyList)
    {
      qDebug() << __FILE__ << __LINE__ << proxy << proxy->getSMName() << proxy->getSMGroup();
    }
#endif
  } // foreach (server)

  return true;
} // closeProject()
