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

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

#include "vtkObjectFactory.h"
#include "vtkInstantiator.h"
#include "vtkVVFileInstancePool.h"
#include "vtkXMLDataElement.h"
#include "vtkKWApplication.h"
#include "vtkVVFileInstance.h"

#include "XML/vtkXMLVVFileInstancePoolWriter.h"
#include "KWVolViewInstantiator.h"

vtkStandardNewMacro(vtkXMLVVFileInstancePoolReader);
vtkCxxRevisionMacro(vtkXMLVVFileInstancePoolReader, "$Revision: 1.16 $");

//----------------------------------------------------------------------------
const char* vtkXMLVVFileInstancePoolReader::GetRootElementName()
{
  return "VVFileInstancePool";
}

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

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

  // Get Attributes

  // File Instances
  
  obj->RemoveAllFileInstances();

  // Backward compat, we used to put them in "FileInstances"

  vtkXMLDataElement *compat_nested_elem = 
    elem->FindNestedElementWithName("FileInstances");
  if (compat_nested_elem)
    {
    elem = compat_nested_elem;
    }

  int idx, nb_nested_elems = elem->GetNumberOfNestedElements();
  for (idx = 0; idx < nb_nested_elems; idx++)
    {
    vtkXMLDataElement *nested_elem = elem->GetNestedElement(idx);
    const char *classname = nested_elem->GetAttribute("ClassName");
    if (classname)
      {
      vtkVVFileInstance *file = vtkVVFileInstance::SafeDownCast(
        vtkInstantiator::CreateInstance(classname));
      if (file)
        {
        file->SetApplication(obj->GetApplication());
        
        vtkXMLObjectReader *xmlr = file->GetNewXMLReader();
        xmlr->Parse(nested_elem);
        obj->AddFileInstance(file);
        file->Delete();
        xmlr->Delete();
        }
      }
    }

  return 1;
}

//----------------------------------------------------------------------------
void vtkXMLVVFileInstancePoolReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
