// This may look like C code, but it is really -*- C++ -*-
// Gestion de block de donnees swapable
//                         R. Ansari  Mars 2005
// LAL (Orsay) / IN2P3-CNRS  DAPNIA/SPP (Saclay) / CEA
#ifndef PPFSWAPPER_H
#define PPFSWAPPER_H


#include "machdefs.h"
#include "swsegdb.h"
#include "ppersist.h"
#include "ppftpointerio.h"

/*!
  \class SOPHYA::PPFDataSwapper
  \ingroup BaseTools
  Implementation of SOPHYA::DataSwapperInterface interface on PPF streams 
  (POutPersist , PInPersist) to be used with SOPHYA::SwSegDataBlock classes.
  the identifier idx is not used in this implementation. In case of re-writing 
  to swap, the previous position is ignored, the data is re-written to swap 
  and a new swap position is returned.
*/

namespace SOPHYA {

template <class T> 
class PPFDataSwapper : public DataSwapperInterface<T> {
public:
  PPFDataSwapper() { ppfos = NULL; ppfis = NULL;}
  PPFDataSwapper(POutPersist & os) { ppfos = &os; ppfis = NULL;}
  PPFDataSwapper(PInPersist & is) { ppfos = NULL; ppfis = &is;}
  PPFDataSwapper(PInPersist & is, POutPersist & os) { ppfos = &os; ppfis = &is;}

  inline PInPersist & InStream() { return *ppfis; }
  inline POutPersist & OutStream() { return *ppfos; }
  inline void SetInStream(PInPersist & is) { ppfis = &is; }
  inline void SetOutStream(POutPersist & os) { ppfos = &os; }

  // Operateur = , on recopie les pointeurs des streams 
  inline PPFDataSwapper<T>& operator = (PPFDataSwapper<T> const & a) 
  { ppfis = a.ppfis;  ppfos = a.ppfos; return *this; }

  virtual int_8 WriteToSwap(const T * d, size_t sz, int_8 idx, int_8 oswp=0, bool osw=false)
  {
    if (ppfos == NULL) 
      throw NotAvailableOperation("PPFDataSwapper<T>::WriteToSwap() - No POutPersist stream !");
    int_8 tag = ppfos->WritePositionTag();
    PPF_TPointer_IO<T>::Write(*ppfos, d, sz);
    return tag;
  }
  virtual void  ReadFromSwap(int_8 idx, int_8 swp, T* d, size_t sz)
  {
    if (ppfis == NULL) 
      throw NotAvailableOperation("PPFDataSwapper<T>::ReadFromSwap() - No PInPersist stream !");
    bool ok = ppfis->GotoPositionTag(swp);
    PPF_TPointer_IO<T>::Read(*ppfis, d, sz);
    return;
  }
  virtual DataSwapperInterface<T>* Clone()
  {
    PPFDataSwapper<T> * rsw = new PPFDataSwapper<T> ;
    (*rsw) = *this; 
    return rsw;
  }
protected:
  POutPersist* ppfos;
  PInPersist* ppfis;
};

} // Fin du namespace

#endif
