#include "my_throw.h"
#include "GIFTExceptions.h"
#include "CAccessor.h"
#include "CAccessorFactory.h"
#include "CAccessorFactoryContainer.h"


/** configure this */
void CAccessorFactoryContainer::configure(const CXMLElement* inConfigurationData){
  mConfigurationData=inConfigurationData;
};
/**
     The destructor destroys the CContentElements properly 
  */
CAccessorFactoryContainer::~CAccessorFactoryContainer(){
  for(CContent::iterator i=mContent.begin();
      i!=mContent.end();
      i++){
    delete i->second.mAccessor;
    delete i->second.mFactory;
  }
};
/** 
      adding a factory to the content
   */
void CAccessorFactoryContainer::registerFactory(CAccessorFactory* inFactory,
						string inName){
  CContent::const_iterator lFound=mContent.find(inName);
  if(lFound!=mContent.end()){
    my_throw(VEProgrammingMistake("CAccessorFactoryContainer::registerFactory"));
  }else{
    mContent[inName].mFactory=inFactory;
    mContent[inName].mAccessor=0;
    mContent[inName].mOpenCloseCounter=0;
  }
};
/**
     opening an accessor:
     if the accessor is already constructed,
     then simply give the pointer,
     otherwhise construct a new one 
     using the appropriate factory

  */
CAccessor* CAccessorFactoryContainer::openAccessor(string inName){
  CContent::const_iterator lFound=mContent.find(inName);
  if(lFound==mContent.end()){
    return 0;
  }else{
    if(!(mContent[inName].mOpenCloseCounter)){
      mContent[inName].mOpenCloseCounter++;
      mContent[inName].mAccessor=
	mContent[inName].mFactory->makeAccessor(*mConfigurationData);
      cout << "NEW ACCESSOR" << endl;
    }
    return mContent[inName].mAccessor;
  }
};
/**
   closing an accessor.
   If there have been as many openAccessor 
   as closeAccessor calls, the accessor will
   be delete-d.
*/
void CAccessorFactoryContainer::closeAccessor(string inName){
  CContent::const_iterator lFound=mContent.find(inName);
  if((lFound!=mContent.end())
     &&
     !(--(mContent[inName].mOpenCloseCounter))){
    delete mContent[inName].mAccessor;
    mContent[inName].mAccessor=0;
  }
};
  
    

  
