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

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/DirectoryItem.h"
#include "smtk/attribute/DoubleItem.h"
#include "smtk/attribute/FileItem.h"
#include "smtk/attribute/GroupItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/ModelEntityItem.h"
#include "smtk/attribute/Registrar.h"
#include "smtk/attribute/Resource.h"
#include "smtk/attribute/ResourceItem.h"
#include "smtk/attribute/StringItem.h"

#include "smtk/io/WriteMesh.h"

#include "smtk/mesh/core/Resource.h"
#include "smtk/mesh/resource/Registrar.h"

#include "smtk/operation/Registrar.h"
#include "smtk/operation/operators/ImportPythonOperation.h"

#include "smtk/session/rgg/Registrar.h"
#include "smtk/session/rgg/Resource.h"
#include "smtk/session/rgg/Session.h"

#include "smtk/session/rgg/operators/CreateModel.h"

#include "smtk/simulation/proteus/Registrar.h"

#include "smtk/model/EntityRef.h"
#include "smtk/model/Model.h"

#include "smtk/io/AttributeReader.h"
#include "smtk/io/Logger.h"

//force to use filesystem version 3
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

#include "smtk/session/rgg/testing/cxx/TestModel.h"

namespace
{
std::string dataRoot = DATA_DIR;
std::string writeRoot = SCRATCH_DIR;
std::string assygenExe = ASSYGEN_EXE;
std::string coregenExe = COREGEN_EXE;
std::string cubitExe = CUBIT_EXE;
std::string mcc3Exe = MCC3_EXE;

bool exists(std::string filename)
{
  return ::boost::filesystem::exists(::boost::filesystem::path(filename));
}

bool findExecutables()
{
  //verify the executables we need to generate a mesh and cross section file exist
  return (exists(assygenExe) && exists(coregenExe) && exists(cubitExe) && exists(mcc3Exe));
}

void cleanup(const std::string& directory_path)
{
  //first verify the directory exists
  ::boost::filesystem::path path(directory_path);
  if (::boost::filesystem::is_directory(path))
  {
    //remove the file_path if it exists.
    ::boost::filesystem::remove_all(path);
  }
}
}


int TestProteusSNSimulationWorkflow(int argc, char* argv[])
{
  if (findExecutables() == false)
  {
    std::cerr << "Could not locate the necessary executables to run this test.\n";
    std::cerr << "Please set ASSYGEN_EXE, COREGEN_EXE, CUBIT_EXE and MCC3_EXE\n";
    std::cerr << "during configuration.\n";
    std::cerr << "Current values:" << "\n";
    std::cerr << "  ASSYGEN_EXE = " << assygenExe << "\n";
    std::cerr << "  COREGEN_EXE = " << coregenExe << "\n";
    std::cerr << "  CUBIT_EXE = " << cubitExe << "\n";
    std::cerr << "  MCC3_EXE = " << mcc3Exe << "\n";
    return 125;
  }

  // Create a resource manager
  smtk::resource::Manager::Ptr resourceManager = smtk::resource::Manager::create();

  // Register necessary resources to the resource manager
  {
    smtk::attribute::Registrar::registerTo(resourceManager);
    smtk::mesh::Registrar::registerTo(resourceManager);
    smtk::session::rgg::Registrar::registerTo(resourceManager);
  }

  // Create an operation manager
  smtk::operation::Manager::Ptr operationManager = smtk::operation::Manager::create();

  // Register necessary operators to the operation manager
  {
    smtk::attribute::Registrar::registerTo(operationManager);
    smtk::operation::Registrar::registerTo(operationManager);
    smtk::session::rgg::Registrar::registerTo(operationManager);
    smtk::simulation::proteus::Registrar::registerTo(operationManager);
  }

  // Register the resource manager to the operation manager (newly created
  // resources will be automatically registered to the resource manager).
  operationManager->registerResourceManager(resourceManager);

  // Construct an RGG model
  smtk::model::ResourcePtr resource = smtk::session::rgg::test::constructTestModel();
  // smtk::model::ResourcePtr resource = smtk::session::rgg::test::constructTest11TwoDantModel();
  smtk::model::Model model =
    resource->entitiesMatchingFlagsAs<smtk::model::EntityRefArray>(smtk::model::MODEL_ENTITY)[0];

  // Generate a mesh for the model
  smtk::mesh::Resource::Ptr meshResource;
  {
    // Create a "Generate Mesh" operation
    smtk::operation::Operation::Ptr generateMeshOp =
      operationManager->create("rggsession.session.generate_mesh.GenerateMesh");

    if (!generateMeshOp)
    {
      std::cerr << "Could not create \"generate mesh\" operation\n";
      return 1;
    }

    generateMeshOp->parameters()->associate(model.component());

    generateMeshOp->parameters()->findFile("assygen")->setIsEnabled(true);
    generateMeshOp->parameters()->findFile("assygen")->setValue(assygenExe);
    generateMeshOp->parameters()->findFile("coregen")->setIsEnabled(true);
    generateMeshOp->parameters()->findFile("coregen")->setValue(coregenExe);
    generateMeshOp->parameters()->findFile("cubit")->setIsEnabled(true);
    generateMeshOp->parameters()->findFile("cubit")->setValue(cubitExe);

    if (!generateMeshOp->ableToOperate())
    {
      std::cerr << "\"generate mesh\" operator unable to operate\n";
      return 1;
    }

    smtk::operation::Operation::Result generateMeshOpResult = generateMeshOp->operate();

    if (generateMeshOpResult->findInt("outcome")->value() !=
        static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "\"generate mesh\" operator failed to generate a mesh\n";
      std::cerr << generateMeshOp->log().convertToString(true) << "\n";
      return 1;
    }

    meshResource = std::dynamic_pointer_cast<smtk::mesh::Resource>(
      generateMeshOpResult->findResource("resource")->value());
  }

  // Construct PYARC simulation attributes for MCC3 and DIF3D
  smtk::attribute::ResourcePtr pyarcSimulationAttributes;
  smtk::attribute::AttributePtr mcc3Att;
  {
    pyarcSimulationAttributes = resourceManager->create<smtk::attribute::Resource>();

    smtk::io::Logger logger;
    smtk::io::AttributeReader reader;
    // the attribute reader returns true on failure...
    if (reader.read(pyarcSimulationAttributes,
                    dataRoot + "/../smtk/simulation/pyarc/templates/mcc3.sbt", true, logger))
    {
      std::cerr << "Import PYARC simulation attributes failed\n";
      std::cerr << logger.convertToString(true) << "\n";
      return 1;
    }

    mcc3Att = pyarcSimulationAttributes->createAttribute("mcc3-instance", "mcc3");

    if (!mcc3Att->isValid())
    {
      std::cerr << "Failed to set dummy mcc3 values\n";
      return 1;
    }
  }

  std::string crossSectionsFile;
  {
    // Create a "Generate Cross Sections" operation
    smtk::operation::Operation::Ptr generateCrossSectionsOp = operationManager->create(
      "rggsession.simulation.proteus.generate_cross_sections.GenerateCrossSections");

    if (!generateCrossSectionsOp)
    {
      std::cerr << "Could not create \"generate cross sections\" operation\n";
      return 1;
    }

    crossSectionsFile = writeRoot + "/crosssections.isotxs";

    generateCrossSectionsOp->parameters()->associate(model.component());

    generateCrossSectionsOp->parameters()->findFile("mcc3.x")->setIsEnabled(true);
    generateCrossSectionsOp->parameters()->findFile("mcc3.x")->setValue(mcc3Exe);
    generateCrossSectionsOp->parameters()->findComponent("mcc3_atts")->setValue(mcc3Att);
    generateCrossSectionsOp->parameters()->findFile("filename")->setValue(crossSectionsFile);

    smtk::operation::Operation::Result generateCrossSectionsOpResult =
      generateCrossSectionsOp->operate();

    if (generateCrossSectionsOpResult->findInt("outcome")->value() !=
        static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED) ||
        !exists(crossSectionsFile))
    {
      std::cerr <<"\"generate cross sections\" operator failed to generate a cross sections file\n";
      std::cerr << generateCrossSectionsOp->log().convertToString(true) << "\n";
      return 1;
    }
  }

  std::string outputDirectory = writeRoot + "/proteus-sn";

  // Clean up generated files from prior runs
  cleanup(outputDirectory);

  // Construct PROTEUS simulation attributes
  smtk::attribute::ResourcePtr proteusSimulationAttributes;
  {
    proteusSimulationAttributes = resourceManager->create<smtk::attribute::Resource>();

    smtk::io::Logger logger;
    smtk::io::AttributeReader reader;
    // the attribute reader returns true on failure...
    if (reader.read(proteusSimulationAttributes,
                    dataRoot + "/../smtk/simulation/proteus/templates/driver_input.sbt", true, logger))
    {
      std::cerr << "Import PROTEUS-SN simulation attributes failed\n";
      std::cerr << logger.convertToString(true) << "\n";
      return 1;
    }

    auto driverAtt = proteusSimulationAttributes->createAttribute("driver_input", "driver_input");
    {
      // Create general items
      driverAtt->findInt("THETA_RESOLUTION")->setValue(2);

      // TODO: should these be generated if they don't exist?
      driverAtt->findFile("SOURCEFILE_MESH")->setValue(outputDirectory + "/sn2nd.nemesh");
      driverAtt->findFile("SOURCEFILE_XS")->setValue(crossSectionsFile);
      driverAtt->findFile("SOURCEFILE_MATERIAL")->setValue(outputDirectory + "/sn2nd.assignment");
      driverAtt->findFile("EXPORT_FILE")->setValue(outputDirectory + "/sn2nd.pmo");
      if (!driverAtt->isValid())
      {
        std::cerr << "Invalid driver attribute\n";
        return 1;
      }
    }
  }

  // Construct the simulation export operation using its unique name
  {
    smtk::operation::Operation::Ptr exportOp = operationManager->create(
      "rggsession.simulation.proteus.export_to_proteus_sn.export_to_proteus_sn");

    if (!exportOp)
    {
      std::cerr << "No \"export_to_proteus_sn\" operation\n";
      return 1;
    }

    exportOp->parameters()->findComponent("model")->setValue(model.component());
    exportOp->parameters()->findResource("mesh")->setValue(meshResource);
    exportOp->parameters()->findResource("attributes")->setValue(proteusSimulationAttributes);
    exportOp->parameters()->findDirectory("OutputDirectory")->setValue(outputDirectory);

    if (!exportOp->ableToOperate())
    {
      std::cerr << "\"export_to_proteus_sn\" operation unable to operate\n";
      return 1;
    }

    auto result = exportOp->operate();

    if (result->findInt("outcome")->value() !=
        static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "\"export_to_proteus_sn\" operation failed\n";
      std::cerr << exportOp->log().convertToString(true) << "\n";
      return 1;
    }
  }

  smtk::io::writeMesh(outputDirectory + "/sn2nd.exo", meshResource);

  return 0;
}
