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

// #include "smtk/simulation/windtunnel/TaskFlow.h"
#include "smtk/simulation/windtunnel/qt/qtSessionData.h"

// SMTK
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/extension/paraview/appcomponents/pqSMTKBehavior.h"
#include "smtk/extension/paraview/appcomponents/pqSMTKWrapper.h"
#include "smtk/io/Logger.h"
#include "smtk/operation/Manager.h"
#include "smtk/operation/Operation.h"
#include "smtk/project/Project.h"
#include "smtk/project/operators/Write.h"

// ParaView (client side)
#include "pqActiveObjects.h"
#include "pqCoreUtilities.h"
#include "pqServer.h"

#include <QAction>
#include <QDebug>
#include <QDir>
#include <QMessageBox>
#include <QString>
#include <QtGlobal>

#include <nlohmann/json.hpp>

#include <string>

namespace
{
const int OP_SUCCEEDED = static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED);
}

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

void pqWindTunnelSaveProjectReaction::onTriggered()
{
  pqWindTunnelSaveProjectBehavior::instance()->saveProject();
}

//-----------------------------------------------------------------------------
bool pqWindTunnelSaveProjectBehavior::saveProject()
{
  // Get current project
  auto* sessionData = smtk::simulation::windtunnel::qtSessionData::instance();
  auto project = sessionData->project();
  if (project == nullptr)
  {
    qWarning() << "Internal error - no active project.";
    return false;
  }

  // Access the active server to get the operation manager
  pqServer* server = pqActiveObjects::instance().activeServer();
  pqSMTKWrapper* wrapper = pqSMTKBehavior::instance()->resourceManagerForServer(server);
  auto opManager = wrapper->smtkOperationManager();

  // Instantiate the Write operator
  auto writeOp = opManager->create<smtk::project::Write>();
  assert(writeOp != nullptr);

  writeOp->parameters()->associate(project);
  auto result = writeOp->operate();
  int outcome = result->findInt("outcome")->value();
  if (outcome != OP_SUCCEEDED)
  {
    std::string log = writeOp->log().convertToString();
    qWarning() << QString::fromStdString(log);

    QString msg = "There was an error saving the project."
                  " Check the Output Messages panel for details.";
    QMessageBox::warning(
      pqCoreUtilities::mainWidget(), "Failed to save project", msg, QMessageBox::Close);
    return false;
  }
  qInfo() << "Saved project";

  // // Write TaskFlow file
  // auto taskFlow = sessionData->taskFlow();
  // nlohmann::json j = taskFlow;
  // QDir projectDir(sessionData->projectDirectory());
  // QString jsonPath = projectDir.absoluteFilePath("taskflow.json");
  // QFile file(jsonPath);
  // if (!file.open(QFile::WriteOnly))
  // {
  //   qWarning() << "Fail to write" << jsonPath;
  // }
  // else
  // {
  //   QTextStream out(&file);
  //   out << j.dump(2).c_str();
  //   file.close();
  // }

  return true;
} // saveProject()

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

pqWindTunnelSaveProjectBehavior::pqWindTunnelSaveProjectBehavior(QObject* parent)
  : Superclass(parent)
{
}

pqWindTunnelSaveProjectBehavior* pqWindTunnelSaveProjectBehavior::instance(QObject* parent)
{
  if (!g_instance)
  {
    g_instance = new pqWindTunnelSaveProjectBehavior(parent);
  }

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

  return g_instance;
}

pqWindTunnelSaveProjectBehavior::~pqWindTunnelSaveProjectBehavior()
{
  if (g_instance == this)
  {
    g_instance = nullptr;
  }

  QObject::disconnect(this);
}
