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

#include "smtk/simulation/ace3p/Project.h"
#include "smtk/simulation/ace3p/Stage.h"

#include "smtk/attribute/Resource.h"
#include "smtk/common/UUID.h"
#include "smtk/model/Resource.h"
#include "smtk/project/ResourceContainer.h"

#include <string>
#include <vector>

// Define how project stages are serialized.
namespace smtk
{
namespace simulation
{
namespace ace3p
{
void to_json(json& j, const std::shared_ptr<Stage>& stage)
{
  //j = stage;
  j["description"] = stage->description();
  j["attribute"] = stage->attributeResource()->id();

  // Allow model resource to be optional
  if (stage->modelResource() != nullptr)
  {
    j["model"] = stage->modelResource()->id();
  }
}

std::shared_ptr<Stage> parse_json(const json& j, std::shared_ptr<Project> project)
{
  // Get attribute resource
  std::string attUuidString = j["attribute"].get<std::string>();
  smtk::common::UUID attUuid(attUuidString);
  smtk::attribute::ResourcePtr attResource =
    project->resources().get<smtk::attribute::Resource>(attUuid);

  // Get optional model resource
  smtk::model::ResourcePtr modelResource;
  if (j.contains("model"))
  {
    std::string modelUuidString = j["model"].get<std::string>();
    smtk::common::UUID modelUuid(modelUuidString);
    modelResource = project->resources().get<smtk::model::Resource>(modelUuid);
  }

  // Get description
  std::string description = j["description"].get<std::string>();

  // Create stage instance
  Stage stage(attResource, modelResource, project->jobsManifest(), description);

  // Return shared pointer
  std::shared_ptr<Stage> stagePtr = std::make_shared<Stage>(stage);
  return stagePtr;
}

} // namespace ace3p
} // namespace simulation
} // namespace smtk
