//=========================================================================
//  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/session/rgg/json/jsonPin.h"

#include <iostream>

namespace smtk
{
namespace session
{
namespace rgg
{
using json = nlohmann::json;

SMTKRGGSESSION_EXPORT void to_json(
  json& j, const Pin::Piece& piece)
{
  j = json{{"pieceType",static_cast<int>(piece.pieceType)},
  {"length", piece.length},
  {"baseRadius",piece.baseRadius},
  {"topRadius",piece.topRadius}};
}

void from_json(
  const json& j, Pin::Piece& piece)
{
  try
  {
    piece.pieceType = static_cast<Pin::PieceType>(j.at("pieceType"));
    piece.length = j.at("length");
    piece.baseRadius = j.at("baseRadius");
    piece.topRadius = j.at("topRadius");
  }
  catch(json::exception &e)
  {
    std::cerr << e.what() << "\n";
    std::cerr << "Failed to parse a piece in the pin" <<std::endl;
  }
}

void to_json(
  json& j, const Pin::LayerMaterial& lm)
{
  j = json{{"subMaterialIndex", lm.subMaterialIndex},
  {"normRadius", lm.normRadius}};
}

void from_json(
  const json& j, Pin::LayerMaterial& lm)
{
  try
  {
    lm.subMaterialIndex = j.at("subMaterialIndex");
    lm.normRadius = j.at("normRadius");
  }
  catch(json::exception &e)
  {
    std::cerr << e.what() << "\n";
    std::cerr << "Failed to parse a layer material in the pin" <<std::endl;
  }
}

void to_json(json& j, const Pin& pin)
{
  j["name"] = pin.name();
  j["label"] = pin.label();
  j["cellMaterialIndex"] = pin.cellMaterialIndex();
  j["color"] = pin.color();
  j["cutAway"] = pin.isCutAway();
  j["zOrigin"] = pin.zOrigin();
  j["pieces"] = pin.pieces();
  j["layerMaterials"] = pin.layerMaterials();
}

void from_json(const json& j, Pin& pin)
{
  try
  {
    pin.setName(j.at("name"));
    pin.setLabel(j.at("label"));
    pin.setCellMaterialIndex(j.at("cellMaterialIndex"));
    pin.setColor(j.at("color"));
    pin.setCutAway(j.at("cutAway"));
    pin.setZOrigin(j.at("zOrigin"));
    pin.setPieces(j.at("pieces"));
    pin.setLayerMaterials(j.at("layerMaterials"));
  }
  catch(json::exception &e)
  {
    std::cerr << e.what() << "\n";
    std::cerr << "RGG pin does not have a valid json object" << std::endl;
    return;
  }
}

} // namespace rgg
} // namespace session
} // namespace smtk
