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

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

#include "vtkKWScaleBarWidget.h"
#include "vtkObjectFactory.h"
#include "vtkXMLDataElement.h"
#include "vtkActor2D.h"
#include "vtkTextActor.h"

#include "XML/vtkXMLActor2DReader.h"
#include "XML/vtkXMLTextActorReader.h"


vtkStandardNewMacro(vtkXMLKWScaleBarWidgetReader);
vtkCxxRevisionMacro(vtkXMLKWScaleBarWidgetReader, "$Revision: 1.13 $");

//----------------------------------------------------------------------------
const char* vtkXMLKWScaleBarWidgetReader::GetRootElementName()
{
  return "KWScaleBarWidget";
}

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

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

  // Get attributes

  double dbuffer2[2], dbuffer3[3] ;
  float fval;
  const char *cptr;

  if (elem->GetVectorAttribute("Color", 3, dbuffer3) == 3)
    {
    obj->SetColor(dbuffer3);
    }

  cptr = elem->GetAttribute("DistanceUnits");
  if (cptr)
    {
    obj->SetDistanceUnits(cptr);
    }

  /* Unfortunately the below code doesn't work so well in some apps; at
     the time it is unserialized, the renderer this widget is associated to
     may not have been rendered yet, and will use a default 10x10 size. 
     Due to vtkKWScaleBarWidget::SetPosition() code, rounding errors will 
     propagate when converting to normalized coords (back & forth).
     Let's serialize the actors directly
  */
#if 0
  if (elem->GetVectorAttribute("Position", 2, dbuffer2) == 2)
    {
    obj->SetPosition(dbuffer2);
    }

  if (elem->GetScalarAttribute("Size", fval))
    {
    obj->SetSize(fval);
    }
#else

  // Scale bar actor

  vtkXMLActor2DReader *xmlr_sb = vtkXMLActor2DReader::New();
  if (xmlr_sb->IsInElement(elem))
    {
    vtkActor2D *scalebara = obj->GetScaleBarActor();
    if (scalebara)
      {
      xmlr_sb->SetObject(scalebara);
      xmlr_sb->ParseInElement(elem);
      }
    }
  xmlr_sb->Delete();

  // Text actor

  vtkXMLTextActorReader *xmlr_t = vtkXMLTextActorReader::New();
  if (xmlr_t->IsInElement(elem))
    {
    vtkActor2D *texta = obj->GetTextActor();
    if (texta)
      {
      xmlr_t->SetObject(texta);
      xmlr_t->ParseInElement(elem);
      }
    }
  xmlr_t->Delete();

#endif  

  return 1;
}

