/*=========================================================================

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm 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 "XML/vtkXMLVVHandleWidgetWriter.h"

#include "vtkObjectFactory.h"
#include "vtkVVHandleWidget.h"
#include "vtkXMLDataElement.h"
#include "vtkHandleRepresentation.h"
#include "vtkImageActorPointHandleRepresentation3D.h"
#include "XML/vtkXMLHandleRepresentationWriter.h"
#include <vtksys/ios/sstream>

vtkStandardNewMacro(vtkXMLVVHandleWidgetWriter);
vtkCxxRevisionMacro(vtkXMLVVHandleWidgetWriter, "$Revision: 1.4 $");

//----------------------------------------------------------------------------
const char* vtkXMLVVHandleWidgetWriter::GetRootElementName()
{
  return "HandleWidget";
}

//----------------------------------------------------------------------------
const char* vtkXMLVVHandleWidgetWriter::GetRepresentationElementName()
{
  return "Representation";
}

//----------------------------------------------------------------------------
const char* vtkXMLVVHandleWidgetWriter::GetIDElementName()
{
  return "ID";
}

//----------------------------------------------------------------------------
int vtkXMLVVHandleWidgetWriter::AddNestedElements(vtkXMLDataElement *elem)
{
  if (!this->Superclass::AddNestedElements(elem))
    {
    return 0;
    }

  vtkVVHandleWidget *obj = vtkVVHandleWidget::SafeDownCast(this->Object);
  if (!obj)
    {
    vtkWarningMacro(<< "The HandleWidget is not set!");
    return 0;
    }

  // ID of the widget

  vtkXMLDataElement *id_elem = this->NewDataElement();
  vtksys_ios::ostringstream os;
  os << obj->GetID();
  id_elem->AddCharacterData(
    os.str().c_str(), (int)os.str().length());
  elem->AddNestedElement(id_elem);
  id_elem->Delete();
  id_elem->SetName(this->GetIDElementName());
   
  // Representation

  vtkHandleRepresentation *rep = 
    vtkHandleRepresentation::SafeDownCast(obj->GetRepresentation());
  if (rep)
    {
    vtkXMLHandleRepresentationWriter *xmlw = 
      vtkXMLHandleRepresentationWriter::New();
    xmlw->SetObject(rep);
    vtkXMLDataElement *nested_elem = xmlw->CreateInNestedElement(
      elem, this->GetRepresentationElementName());
    xmlw->Delete();
    vtkImageActorPointHandleRepresentation3D *repim3d = 
      vtkImageActorPointHandleRepresentation3D::SafeDownCast(rep);
    if (repim3d)
      {
      nested_elem->SetIntAttribute(
        "DisplayForAllSlices", repim3d->GetDisplayForAllSlices());
      }
    }

  return 1;
}

