//=========================================================================
//  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/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/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/session/rgg/operators/ReadRXFFile.h"

#include "smtk/simulation/pyarc/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;

namespace
{
std::string dataRoot = DATA_DIR;
std::string writeRoot = SCRATCH_DIR;

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

int TestDIF3DSimulationWorkflow(int argc, char* argv[])
{
  // 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::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::pyarc::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::session::rgg::Resource::Ptr resource;
  smtk::model::Model model;
  {
    auto createModelOp = smtk::session::rgg::CreateModel::create();
    if (!createModelOp)
    {
      std::cerr << "No create model operator\n";
      return 1;
    }

    auto createModelOpResult = createModelOp->operate();
    if (createModelOpResult->findInt("outcome")->value() !=
      static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "create model operator failed\n";
      std::cerr << createModelOp->log().convertToString(true) << "\n";
      return 1;
    }

    model = createModelOpResult->findComponent("created")->valueAs<smtk::model::Entity>();
    if (!model.isValid())
    {
      std::cerr << "create model operator constructed an invalid model\n";
      return 1;
    }

    resource = std::dynamic_pointer_cast<smtk::session::rgg::Resource>(model.resource());
  }

  // Populate the model from an RXF file
  {
    auto readRXFOp = smtk::session::rgg::ReadRXFFile::create();
    if (!readRXFOp)
    {
      std::cerr << "No \"Read RXF File\" operator\n";
      return 1;
    }

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

    readRXFOp->parameters()
      ->findFile("filename")
      ->setValue(dataRoot + "/simpleCore.rxf");

    auto readRXFOpResult = readRXFOp->operate();
    if (readRXFOpResult->findInt("outcome")->value() !=
      static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "\"Read RXF File\" operator failed\n";
      std::cerr << readRXFOp->log().convertToString(true) << "\n";
      return 1;
    }
  }

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

    smtk::io::Logger logger;
    smtk::io::AttributeReader reader;
    // the attribute reader returns true on failure...
    if (reader.read(neamsSimulationAttributes,
                    dataRoot + "/neutronics-workflow/neams/NEAMS.sbt", true, logger))
    {
      std::cerr << "Import NEAMS simulation attributes failed\n";
      std::cerr << logger.convertToString(true) << "\n";
      return 1;
    }

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

    {
      // Set dummy parameters to make the mcc3 attribute valid
      mcc3Att->findInt("scattering_order")->setValue(1);

      auto rzmflxCodeOptionsGroup = mcc3Att->findGroup("rzmflx_code_options");
      rzmflxCodeOptionsGroup->findAs<smtk::attribute::StringItem>("R_boundaries")->
        setValue("cylinder0_126125");
      rzmflxCodeOptionsGroup->findAs<smtk::attribute::StringItem>("Z_boundaries")->
        setValue("z38_0");

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

    dif3dAtt = neamsSimulationAttributes->createAttribute("dif3d-instance", "dif3d");

    {
      // Set dummy parameters to make the dif3d attribute valid
      dif3dAtt->findDouble("power")->setValue(1.);

      auto rebusGroup = dif3dAtt->findGroup("rebus");
      rebusGroup->findAs<smtk::attribute::DoubleItem>("cycle_length")->setValue(1.);
      rebusGroup->findAs<smtk::attribute::DoubleItem>("shutdown_time_between_cycle")->setValue(1.);

      auto decayChainGroup = rebusGroup->findAs<smtk::attribute::GroupItem>("decay_chain");
      decayChainGroup->findAs<smtk::attribute::StringItem>("list_isotopes")->setValue(0, "U238");
      decayChainGroup->findAs<smtk::attribute::FileItem>("decay_chain_text_file")->setValue(
        dataRoot + "/neutronics-workflow/neams/NEAMS.sbt");

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

  std::string writeFilePath(writeRoot);
  writeFilePath += "/out.son";
  //writeFilePath += "/" + smtk::common::UUID::random().toString() + ".son";
  {
    auto exportToPyARCOp =
      operationManager->create("rggsession.simulation.pyarc.export_to_pyarc.export_to_pyarc");

    if (!exportToPyARCOp)
    {
      std::cerr << "No export to pyarc operator\n";
      return 1;
    }


    exportToPyARCOp->parameters()->findFile("filename")->setValue(writeFilePath);

    exportToPyARCOp->parameters()->associate(model.component());
    exportToPyARCOp->parameters()->findComponent("mcc3")->setValue(mcc3Att);
    exportToPyARCOp->parameters()->findComponent("dif3d")->setValue(dif3dAtt);

    auto exportToPyARCOpResult = exportToPyARCOp->operate();
    if (exportToPyARCOpResult->findInt("outcome")->value() !=
      static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "export to pyarc operator failed\n";
      std::cerr << exportToPyARCOp->log().convertToString(true) << "\n";
      return 1;
    }

    std::cout<<exportToPyARCOp->log().convertToString(true)<<std::endl;

    cleanup(writeFilePath);
  }

  return 0;
}
