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

  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/vtkXMLVVHandleWidgetReader.h"

#include "vtkObjectFactory.h"
#include "vtkVVHandleWidget.h"
#include "vtkXMLDataElement.h"
#include "vtkHandleRepresentation.h"
#include "vtkImageActorPointHandleRepresentation3D.h"

#include "XML/vtkXMLHandleRepresentationReader.h"
#include "XML/vtkXMLVVHandleWidgetWriter.h"
#include <vtksys/ios/sstream>

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

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

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

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

  // Get nested elements
  
  int nb_nested_elems = elem->GetNumberOfNestedElements();
  for (int idx = 0; idx < nb_nested_elems; idx++)
    {
    vtkXMLDataElement *nested_elem = elem->GetNestedElement(idx);

    // ID

    if (!strcmp(nested_elem->GetName(), 
                vtkXMLVVHandleWidgetWriter::GetIDElementName()))
      {
      const char *cd = nested_elem->GetCharacterData();
      if (cd)
        {
        int ID;
        strstream is;
        is << cd << ends; // no istringstream in VTK
        is >> ID;
        is.rdbuf()->freeze(0);
        obj->SetID(ID);
        }
      }
    }
  
  // Representation

  vtkHandleRepresentation *rep = 
    vtkHandleRepresentation::SafeDownCast(obj->GetRepresentation());
  if (rep)
    {
    vtkXMLHandleRepresentationReader *xmlr = 
      vtkXMLHandleRepresentationReader::New();
    xmlr->SetObject(rep);
    vtkXMLDataElement *nested_elem = xmlr->ParseInNestedElement(
      elem, vtkXMLVVHandleWidgetWriter::GetRepresentationElementName());
    xmlr->Delete();
    vtkImageActorPointHandleRepresentation3D *repim3d = 
      vtkImageActorPointHandleRepresentation3D::SafeDownCast(rep);
    int ival;
    if (repim3d && 
        nested_elem->GetScalarAttribute("DisplayForAllSlices", ival))
      {
      repim3d->SetDisplayForAllSlices(ival);
      }
    obj->WidgetIsDefined();
    }

  return 1;
}

