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

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

#include "vtkKWIcon.h"
#include "vtkObjectFactory.h"
#include "vtkXMLDataElement.h"
#include "vtkKWResourceUtilities.h"

vtkStandardNewMacro(vtkXMLKWIconWriter);
vtkCxxRevisionMacro(vtkXMLKWIconWriter, "$Revision: 1.3 $");

//----------------------------------------------------------------------------
const char* vtkXMLKWIconWriter::GetRootElementName()
{
  return "KWIcon";
}

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

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

  elem->SetIntAttribute("Width", obj->GetWidth());

  elem->SetIntAttribute("Height", obj->GetHeight());

  elem->SetIntAttribute("PixelSize", obj->GetPixelSize());

  return 1;
}

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

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

  // Data

  unsigned long encoded_buffer_length;
  unsigned char *encoded_buffer;

  if (!vtkKWResourceUtilities::EncodeBuffer(
        obj->GetData(), 
        (unsigned long)obj->GetWidth() * 
        (unsigned long)obj->GetHeight() * 
        (unsigned long)obj->GetPixelSize(),
        &encoded_buffer, 
        &encoded_buffer_length, 
        vtkKWResourceUtilities::ConvertImageToHeaderOptionZlib |
        vtkKWResourceUtilities::ConvertImageToHeaderOptionBase64))
    {
    return 0;
    }

  elem->SetCharacterData((const char*)encoded_buffer, encoded_buffer_length);

  delete [] encoded_buffer;

  return 1;
}
