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

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

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

#include "vtkActor2D.h"
#include "vtkTextActor.h"

#include "XML/vtkXMLActor2DWriter.h"
#include "XML/vtkXMLTextActorWriter.h"

vtkStandardNewMacro(vtkXMLKWScaleBarWidgetWriter);
vtkCxxRevisionMacro(vtkXMLKWScaleBarWidgetWriter, "$Revision: 1.9 $");

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

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

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

  elem->SetVectorAttribute("Color", 3, obj->GetColor());

  elem->SetAttribute("DistanceUnits", obj->GetDistanceUnits());

  /* 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
  double pos[2];
  obj->GetPosition(pos);
  elem->SetVectorAttribute("Position", 2, pos);

  elem->SetFloatAttribute("Size", obj->GetSize());
#else

  // Scale bar actor

  vtkActor2D *scalebara = obj->GetScaleBarActor();
  if (scalebara)
    {
    vtkXMLActor2DWriter *xmlw_sb = vtkXMLActor2DWriter::New();
    xmlw_sb->SetObject(scalebara);
    xmlw_sb->CreateInElement(elem);
    xmlw_sb->Delete();
    }

  // Text actor

  vtkActor2D *texta = obj->GetTextActor();
  if (texta)
    {
    vtkXMLTextActorWriter *xmlw_t = vtkXMLTextActorWriter::New();
    xmlw_t->SetObject(texta);
    xmlw_t->CreateInElement(elem);
    xmlw_t->Delete();
    }

#endif

  return 1;
}

