//=========================================================================
//  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/io/AttributeReader.h"
#include "smtk/io/Logger.h"

#include "smtk/session/aeva/operators/CreateAnnotationResource.h"

#include "smtk/session/aeva/CreateAnnotationResource_xml.h"
#include "smtk/session/aeva/Resource.h"
#include "smtk/session/aeva/Session.h"
#include "smtk/session/aeva/aeva_xml.h"

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/Resource.h"
#include "smtk/attribute/ResourceItem.h"

#include "smtk/operation/MarkGeometry.h"

#include "smtk/resource/Manager.h"

#include "smtk/common/Paths.h"

#include <sstream>

// On Windows MSVC 2015+, something is included that defines
// a macro named ERROR to be 0. This causes smtkErrorMacro()
// to expand into garbage (because smtk::io::Logger::ERROR
// gets expanded to smtk::io::Logger::0).
#ifdef ERROR
#undef ERROR
#endif

namespace smtk
{
namespace session
{
namespace aeva
{

CreateAnnotationResource::CreateAnnotationResource() = default;

CreateAnnotationResource::Result CreateAnnotationResource::operateInternal()
{
  smtk::session::aeva::Resource::Ptr modelResource = nullptr;
  smtk::session::aeva::Session::Ptr session = nullptr;
  m_result = this->createResult(CreateAnnotationResource::Outcome::SUCCEEDED);
  // Create an aeva model resource if none was associated:
  this->prepareResourceAndSession(m_result, modelResource, session);

  smtk::attribute::ResourceItem::Ptr created = m_result->findResource("resource");
  auto annotationResource = smtk::attribute::Resource::create();
  smtk::io::AttributeReader reader;
  bool errors =
    reader.readContents(annotationResource, reinterpret_cast<const char*>(aeva_xml), this->log());
  if (errors)
  {
    created->reset(); // Do not hold on to any created resources.
    smtkErrorMacro(this->log(), "Could not apply template.");
    return m_result;
  }
  annotationResource->setName("new anatomical annotations");
  if (created->isSet(0))
  {
    created->appendValue(annotationResource);
    // If created already had a member, then a new model resource
    // was created. Set its name as well:
    modelResource->setName("new anatomical geometry");
  }
  else
  {
    created->setValue(annotationResource);
  }
  annotationResource->associate(modelResource);

  return m_result;
}

const char* CreateAnnotationResource::xmlDescription() const
{
  return CreateAnnotationResource_xml;
}

}
}
}
