// Copyright (c) 1997 by Jim Lynch.
// Copyright (c) 2010-2012 by Philipp Schafft.
// This software comes with NO WARRANTY WHATSOEVER.
//
// This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; version 2 dated June, 1991, or, at your
//    option, any LATER version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this software; see the file COPYING.  If not, write to
//    the Free Software Foundation, 51 Franklin Street, Fifth Floor,
//    Boston, MA 02110-1301, USA.

#ifndef Record_h
#define Record_h

#include "db4++-stuff.h"

#include "str-conversions.h"

// #include <gdbm.h>
#include <malloc.h>
#include <string>
#include <iostream>

class Record
{
protected:
  virtual void Destroy(void)
    {
    }
  
  virtual void SetNull(void)
    {
    }

  virtual void SetFromDataString(const char *theDataString)
    {
    }
  
public:
  Record() { }
  
  virtual ~Record() { }
  
  virtual const char *FormNewDataCString() const
    {
    }

  virtual void Read(Db &handle, const std::string &theKey)
    {
      std::string theValue;
      
      Destroy();
      
      if(::Read(handle, theKey, theValue))
	{
	  SetFromDataString(theValue.c_str());
	}
      else
	{
	  SetNull();
	}

      // const char *key = theKey.c_str();
      //
      // Read(handle, key);
    }
  
  virtual void Read(Db &handle, const char *theKey)
    {
      std::string key(theKey);
      
      Read(handle, key);
      
      // Dbt key((void*) theKey, strlen(theKey) + 1);
      // Dbt content;
      // char * p;
      //
      // handle.get(NULL, &key, &content, 0);
      // p = (char *) content.get_data();
      //
      // Destroy();
      //
      // if(p)
      // {
      //   char *tmp = MakeCStringCopy(p);
      //
      //   SetFromDataString(tmp);
      // }
      // else
      //   SetNull();
    }
  
  virtual void Write(Db &handle, const char *theKey) const
    {
      std::string p(FormNewDataCString());
      std::string key(theKey);
      
      int wrOK = ::Write(handle, key, p);
    }

  virtual void Print(std::ostream &out) const
    {
      const char *p = FormNewDataCString();
      out << p;
      delete[] p;
    }
};

inline std::ostream &operator<<(std::ostream &out, const Record &it)
{
  it.Print(out);

  return out;
}

#endif

