/*
 * databasewrapper.cc
 *
 * Copyright (c) 2002, 2003 Frerich Raabe <raabe@kde.org>
 *
 * 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. For licensing and distribution details, check the
 * accompanying file 'COPYING'.
 */
#include "databasewrapper.h"

#include <kdebug.h>

#include <qfile.h>

#include <sys/types.h>
#include <db.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>

using namespace Barry;

DatabaseWrapper::DatabaseWrapper( const QString &filename )
	: m_database( 0 ),
	m_filename( filename )
{
}

DatabaseWrapper::~DatabaseWrapper()
{
	if ( m_database )
		m_database->close( m_database );
}

bool DatabaseWrapper::open( Flags flags, Format format )
{
	if ( m_database ) {
		kdWarning() << "Database `" << m_filename
		            << "` is already open!" << endl;
		return false;
	}

	m_database = dbopen( QFile::encodeName( m_filename ),
	                     static_cast<int>( flags ),
	                     static_cast<int>( flags ),
	                     ( DBTYPE )format,
	                     0 );

	return m_database != NULL;
}

QString DatabaseWrapper::getEntry( const QString &key_ )
{
	if ( !m_database ) {
		kdWarning() << "Database " << m_filename << " not opened." << endl;
		return QString::null;
	}

	DBT key;
	key.data = ( void * )key_.latin1();
	key.size = key_.length();

	DBT data;
	const int retval = m_database->get( m_database, &key, &data, 0 );

	if ( retval == 1 )
		return QString::null;

	if ( retval == -1 ) {
		kdWarning() << "Database error: " << strerror( errno ) << endl;
		return QString::null;
	}

	return QString::fromLatin1( static_cast<char *>( data.data ), data.size );
}

QStringList DatabaseWrapper::getAllKeys()
{
	QStringList keys;

	if ( !m_database ) {
		kdWarning() << "Database " << m_filename << " not opened." << endl;
		return keys;
	}

	DBT key;
	DBT data;
	m_database->seq( m_database, &key, &data, R_FIRST );
	keys << QString::fromLatin1( static_cast<char *>( key.data ), key.size );

	while ( !m_database->seq( m_database, &key, &data, R_NEXT ) )
		keys << QString::fromLatin1( static_cast<char *>( key.data ), key.size );

	return keys;
}

// vim:ts=4:sw=4:noet:list
