//=========================================================================
//  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/simulation/ace3p/operations/Read.h"

#include "smtk/simulation/ace3p/Metadata.h"
#include "smtk/simulation/ace3p/Project.h"
#include "smtk/simulation/ace3p/json/jsonStage.h"

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/attribute/Definition.h"
#include "smtk/attribute/FileItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/Resource.h"
#include "smtk/attribute/ResourceItem.h"
#include "smtk/attribute/ResourceItemDefinition.h"
#include "smtk/attribute/StringItem.h"
#include "smtk/attribute/StringItemDefinition.h"
#include "smtk/common/UUID.h"
#include "smtk/io/Logger.h"
#include "smtk/model/Resource.h"
#include "smtk/operation/operators/ReadResource.h"
#include "smtk/project/Manager.h"

#include "smtk/project/json/jsonProject.h"

#include "smtk/simulation/ace3p/Read_xml.h"

#include "boost/filesystem.hpp"
#include "boost/system/error_code.hpp"

#include <map>
#include <set>
#include <string>
#include <vector>

// Include sanity checks for job id are uniqueness and assignment to stages
#define CHECK_JOB_DATA 1

namespace
{
///\brief Adds stage to legacy project
void createLegacyStage(std::shared_ptr<smtk::simulation::ace3p::Project> project)
{
  smtk::attribute::ResourcePtr attResource;
  std::set<smtk::attribute::ResourcePtr> attSet =
    project->resources().find<smtk::attribute::Resource>();
  if (!attSet.empty())
  {
    attResource = *attSet.begin();
  }

  smtk::model::ResourcePtr modelResource;
  std::set<smtk::model::ResourcePtr> modelSet = project->resources().find<smtk::model::Resource>();
  if (!modelSet.empty())
  {
    modelResource = *modelSet.begin();

    // Get native mesh filename from metadata
    smtk::simulation::ace3p::Metadata mdata;
    mdata.getFromResource(project);
    std::string nativeFile = mdata.NativeAnalysisMeshLocation;
    modelResource->properties().insert<std::string>(
      smtk::simulation::ace3p::Metadata::METADATA_PROPERTY_KEY, nativeFile);
    modelResource->setClean(false);
  }

  // Extract job ids
  std::shared_ptr<smtk::simulation::ace3p::JobsManifest> manifest = project->jobsManifest();
  std::string jobId;
  std::vector<std::string> jobIdList;
  for (int i = 0; i < static_cast<int>(manifest->size()); ++i)
  {
    manifest->getField(i, "job_id", jobId);
    jobIdList.push_back(jobId);
  }

  // Create Stage instance
  std::string attributeResourceName = "(null name)";
  if (attResource)
  {
    attributeResourceName = attResource->name();
  }
  smtk::simulation::ace3p::Stage stage(
    attResource, modelResource, project->jobsManifest(), attributeResourceName, jobIdList);

  // Update project and mark modified
  std::shared_ptr<smtk::simulation::ace3p::Stage> stagePtr =
    std::make_shared<smtk::simulation::ace3p::Stage>(stage);
  project->addStage(stagePtr);
  project->setClean(false);
}
} // namespace

namespace smtk
{
namespace simulation
{
namespace ace3p
{

void Read::markModifiedResources(Read::Result& result)
{
  int outcome = result->findInt("outcome")->value();
  if (outcome != static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
  {
    return;
  }

  auto resourceItem = result->findResource("resource");
  auto resource = resourceItem->value();
  if (resource != nullptr)
  {
    resource->setClean(!m_modified);
  }
}

Read::Result Read::operateInternal()
{
  m_modified = false;

  std::string filename = this->parameters()->findFile("filename")->value();
  boost::filesystem::path projectFolderPath = boost::filesystem::path(filename).parent_path();
  boost::filesystem::path jobsManifestPath = projectFolderPath / "JobsManifest.json";
  std::ifstream file(filename);
  if (!file.good())
  {
    smtkErrorMacro(log(), "Cannot read file \"" << filename << "\".");
    file.close();
    return this->createResult(smtk::operation::Operation::Outcome::FAILED);
  }

  nlohmann::json j;
  try
  {
    j = nlohmann::json::parse(file);
  }
  catch (...)
  {
    smtkErrorMacro(log(), "Cannot parse file \"" << filename << "\".");
    file.close();
    return this->createResult(smtk::operation::Operation::Outcome::FAILED);
  }
  file.close();

  // Create a new project for the import
  auto projectptr = this->projectManager()->create(j.at("type").get<std::string>());

  // Transcribe project data into the project
  smtk::project::from_json(j, projectptr);

  // auto project = this->projectManager()->create(j.at("type").get<std::string>());
  // cast to an ace3p project
  auto project = smtk::static_pointer_cast<smtk::simulation::ace3p::Project>(projectptr);

  if (project == nullptr)
  {
    smtkErrorMacro(
      this->log(), "Cannot load project of type \"" << j.at("type").get<std::string>() << "\"");
    return this->createResult(smtk::operation::Operation::Outcome::FAILED);
  }
  // project->setId(projectId);
  project->setLocation(filename);

  // read the Jobs Manifest from file
  if (!project->readJobsManifest())
  {
    smtkErrorMacro(this->log(), "Cannot load project JobsManifest");
    return this->createResult(smtk::operation::Operation::Outcome::FAILED);
  }

  // Read project stages
  if (j.find("stages") == j.end())
  {
    smtkInfoMacro(this->log(), "Converting legacy project to multi-stage format.");
    createLegacyStage(project);
    m_modified = true;
  }
  else
  {
    // Read stages and add to project
    nlohmann::json jStages = j["stages"];
    nlohmann::json::iterator it;
    for (it = jStages["stages"].begin(); it != jStages["stages"].end(); ++it)
    {
      nlohmann::json jStage = *it;
      std::shared_ptr<Stage> stagePtr = parse_json(jStage, project);
      project->addStage(stagePtr);
    }

    // Construct job table to map stage uuid to list of job ids
    std::map<std::string, std::vector<std::string>> jobTable;
    // Create set<jobID> to make sure there aren't any duplicate job ids
    std::set<std::string> jobIdSet;

    std::shared_ptr<smtk::simulation::ace3p::JobsManifest> manifest = project->jobsManifest();
    std::string analysisId;
    std::string jobId;
    for (int i = 0; i < manifest->size(); ++i)
    {
      manifest->getField(i, "analysis_id", analysisId);
      if (jobTable.find(analysisId) == jobTable.end())
      {
        jobTable[analysisId] = std::vector<std::string>();
      }
      manifest->getField(i, "job_id", jobId);
#if CHECK_JOB_DATA
      if (jobIdSet.find(jobId) != jobIdSet.end())
      {
        smtkWarningMacro(this->log(), "Warning: JobId " << jobId << " occurs twice in manifest.");
        continue;
      }
      jobIdSet.insert(jobId);
#endif
      jobTable[analysisId].push_back(jobId);
    }

    // Copy data from jobTable into each stage
    // Erase entries from the job table as they are traversed, so that
    // we can check for orphan job ids.
    for (std::size_t i = 0; i < project->numberOfStages(); ++i)
    {
      std::shared_ptr<Stage> stage = project->stage(i);
      analysisId = stage->attributeResource()->id().toString();
      auto iter = jobTable.find(analysisId);
      if (iter != jobTable.end())
      {
        stage->initJobIds(iter->second);
        jobTable.erase(iter);
      }
    }

#if CHECK_JOB_DATA
    // Sanity check that jobTable is empty
    if (!jobTable.empty())
    {
      smtkWarningMacro(this->log(), "Job manifest contains records not assigned to any stage");
    }
#endif

    // Set current stage
    int index = jStages["index"].get<int>();
    project->setCurrentStage(index, false);
  }

  Result result = this->createResult(smtk::operation::Operation::Outcome::SUCCEEDED);

  {
    smtk::attribute::ResourceItem::Ptr created = result->findResource("resource");
    created->setValue(project);
  }

  return result;
}

const char* Read::xmlDescription() const
{
  return Read_xml;
}

smtk::resource::ResourcePtr read(const std::string& filename)
{
  Read::Ptr read = Read::create();
  read->parameters()->findFile("filename")->setValue(filename);
  Read::Result result = read->operate();
  if (result->findInt("outcome")->value() != static_cast<int>(Read::Outcome::SUCCEEDED))
  {
    return smtk::resource::ResourcePtr();
  }
  return result->findResource("resource")->value();
}
} // namespace ace3p
} // namespace simulation
} // namespace smtk
