//=========================================================================
//  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/ComponentItem.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/Resource.h"
#include "smtk/attribute/StringItem.h"

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

#include "smtk/session/rgg/operators/AddMaterial.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"

#include <fstream>

//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);
  }
}

void addMaterial(smtk::model::Model& model, const std::string& name, const std::string& label,
                 const std::array<double, 4>& color)
{
  auto op = smtk::session::rgg::AddMaterial::create();
  auto parameters = op->parameters();
  parameters->associate(model.component());
  parameters->findString("name")->setValue(name);
  parameters->findString("label")->setValue(label);
  for (std::size_t i = 0; i < 4; i++)
  {
    parameters->findDouble("color")->setValue(i, color[i]);
  }
  parameters->findDouble("temperature")->setValue(273.);
  parameters->findDouble("density")->setValue(1.);
  parameters->findString("component")->setValue(0, "h2");
  parameters->findDouble("content")->setValue(0, 1.);

  auto result = op->operate();
  if (result->findInt("outcome")->value() !=
      static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
  {
    std::cerr << "add material failed\n";
  }
}

void defineMaterials(smtk::model::Model& model)
{
  addMaterial(model, "UnknownMaterial", "Unknown", {1, 1, 1, 1});
  addMaterial(model, "absorber", "absorber", {0.700008, 0.2, 0.700008, 1});
  addMaterial(model, "activecore", "activecore", {1, 0.500008, 0.300008, 1});
  addMaterial(model, "BurnPoison", "BP", {0.45098, 0.45098, 0.45098, 1});
  addMaterial(model, "Cell_Fuel", "CF", {1, 0.168353, 0.0217288, 1});
  addMaterial(model, "CellCoolant", "CC", {0.728191, 0.939208, 0.992157, 1});
  addMaterial(model, "CellFHH", "FH", {0.780392, 0.913725, 0.752941, 1});
  addMaterial(model, "cladding", "cladding", {0.749996, 0.749996, 0.749996, 1});
  addMaterial(model, "ControlCell", "CO", {0.854902, 0.854902, 0.921569, 1});
  addMaterial(model, "controlrod", "controlrod", {0.729, 0.893996, 0.702007, 1});
  addMaterial(model, "coolant", "coolant", {0.300008, 0.500008, 1, 0.500008});
  addMaterial(model, "duct", "duct", {0.300008, 0.300008, 1, 0.500008});
  addMaterial(model, "DuctHandlingSocket", "HD", {0.945098, 0.411765, 0.0745098, 1});
  addMaterial(model, "follower", "follower", {0.749996, 0.2, 0.749996, 1});
  addMaterial(model, "FollowerSodium", "FS", {0.988235, 0.733333, 0.631373, 1});
  addMaterial(model, "fuel", "fuel", {1, 0.100008, 0.100008, 1});
  addMaterial(model, "gap", "gap", {0, 0, 0, 0});
  addMaterial(model, "gasplenum", "gasplenum", {0.300008, 1, 0.500008, 1});
  addMaterial(model, "graphite", "graphite", {0.4, 0.4, 0.4, 1});
  addMaterial(model, "guidetube", "guidetube", {0.6, 0.6, 0.6, 1});
  addMaterial(model, "HandlingSocket", "HS", {0.254902, 0.670588, 0.364706, 1});
  addMaterial(model, "interassemblygap", "interassemblygap", {0, 0, 0, 0});
  addMaterial(model, "loadpad", "loadpad", {0.4, 0.4, 0.4, 1});
  addMaterial(model, "LowerReflector", "LR", {0.258824, 0.572549, 0.776471, 1});
  addMaterial(model, "metal", "metal", {0.6, 0.6, 0.6, 1});
  addMaterial(model, "outerduct", "outerduct", {0.2, 0.2, 0.2, 1});
  addMaterial(model, "reflector", "reflector", {0.500008, 0.500008, 1, 1});
  addMaterial(model, "restraintring", "restraintring", {0.4, 0.4, 0.4, 1});
  addMaterial(model, "shield", "shield", {0.996002, 0.697993, 0.297993, 1});
  addMaterial(model, "SmallCoolant", "SC", {0.776471, 0.858824, 0.937255, 1});
  addMaterial(model, "sodium", "sodium", {1, 1, 0.4, 0.700008});
  addMaterial(model, "SodiumDuct", "NA", {1, 0.985595, 0.0344549, 0.540002});
  addMaterial(model, "water", "water", {0.650996, 0.740993, 0.859007, 0.500008});
}
}

int ExportToPyARCOp(int argc, char* argv[])
{
  // Create a resource manager
  smtk::resource::Manager::Ptr resourceManager = smtk::resource::Manager::create();

  // Register rgg 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 rgg operators to the operation manager
  {
    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);

  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";
      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());
  }

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

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

    std::string inputFilePath = dataRoot + "/sampleCore.rxf";
    readRXFOp->parameters()
      ->findFile("filename")
      ->setValue(inputFilePath);

    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;
    }
  }

  defineMaterials(model);

  // 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 writeFilePath(writeRoot);
  writeFilePath += "/targetCore.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);

    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;
    }

    // Compare the generated file and validation file
    std::string targetFilePath = dataRoot + "/SampleCore.son";
    {
      std::ifstream f1(targetFilePath, std::ifstream::binary | std::ifstream::ate);
      std::ifstream f2(writeFilePath, std::ifstream::binary | std::ifstream::ate);

      if (f1.fail() || f2.fail())
      {
        std::cerr << "Could not read in target or generated file\n\n";
        std::cerr << "target son file: " << targetFilePath << "\n";
        std::cerr << "generated son file: " << writeFilePath << "\n";
        return 1;
      }

      f1.seekg(0, std::ifstream::beg);
      f2.seekg(0, std::ifstream::beg);

      // export_to_pyarc writes a generation tag as the first line. We omit it
      // when comparing against our target file
      f2.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

      if (!std::equal(std::istreambuf_iterator<char>(f1.rdbuf()), std::istreambuf_iterator<char>(),
                      std::istreambuf_iterator<char>(f2.rdbuf())))
      {
        std::cerr << "target and generated files are different\n\n";
        std::cerr << "target son file: " << targetFilePath << "\n";
        std::cerr << "generated son file: " << writeFilePath << "\n";
        return 1;
      }
    }

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

    cleanup(writeFilePath);
  }

  return 0;
}
