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

#include "smtk/resource/json/Helper.h"
#include "smtk/resource/json/jsonResource.h"

#include "smtk/project/json/jsonOperationFactory.h"
#include "smtk/project/json/jsonResourceContainer.h"
#include "smtk/task/json/Helper.h"
#include "smtk/task/json/jsonManager.h"
#include "smtk/task/json/jsonTask.h"
#include "smtk/task/json/jsonFillOutAttributes.h"
#include "smtk/task/json/jsonGatherResources.h"

// Define how projects are serialized.
namespace smtk
{
namespace project
{
void to_json(json& j, const ProjectPtr& project)
{
  smtk::resource::to_json(j, std::static_pointer_cast<smtk::resource::Resource>(project));

  to_json(j["resources"], project->resources(), project);
  to_json(j["operations"], project->operations());

  // Fetch the managers object from the active resource helper and push
  // a task helper onto the stack with that managers object and our project's
  // task manager.
  auto& resourceHelper = smtk::resource::json::Helper::instance();
  auto& taskHelper = smtk::task::json::Helper::pushInstance(
    project->taskManager(), resourceHelper.managers());
  (void)taskHelper;
  j["task_manager"] = project->taskManager();
  smtk::task::json::Helper::popInstance();

  j["conceptual_version"] = project->version();
}

void from_json(const json& j, ProjectPtr& project)
{
  if (!project)
  {
    return;
  }

  smtk::resource::ResourcePtr tmp = std::static_pointer_cast<smtk::resource::Resource>(project);
  smtk::resource::from_json(j, tmp);

  from_json(j["resources"], project->resources(), project);
  from_json(j["operations"], project->operations());
  auto it = j.find("task_manager");
  if (it != j.end())
  {
    from_json(*it, project->taskManager());
  }

  project->setVersion(j["conceptual_version"]);
}
} // namespace project
} // namespace smtk
