// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <OB/CORBA.h>
#include <OB/TemplateI.h>

#include <Database.h>

#ifndef HAVE_NO_EXPLICIT_TEMPLATES
template class OBFixSeq< DBRecordData* >;
#else
#ifdef HAVE_PRAGMA_DEFINE
#pragma define(OBFixSeq< DBRecordData* >)
#endif
#endif

// ----------------------------------------------------------------------
// Database destructor
// ----------------------------------------------------------------------
Database::~Database()
{
    for(CORBA_ULong i = 0; i < records_.length(); ++i)
	delete records_[i];
}

// ----------------------------------------------------------------------
// Database public member implementation
// ----------------------------------------------------------------------

//
// Destroy the record with `key' in the database.  If the record
// does not exist, then return false, true otherwise.
//
bool
Database::destroy(long key)
{
    for(CORBA_ULong i = 0; i < records_.length(); ++i)
    {
	//
	// Found the record?
	//
	if(records_[i] -> key == key)
	{
	    //
	    // Delete the record.
	    //
	    delete records_[i];

	    //
	    // Delete the storage, and shrink the database by one
	    // record.
	    //
	    for(CORBA_ULong j = i+1; j < records_.length(); ++j)
	    {
		records_[j-1] = records_[j];
	    }
	    records_.length(records_.length()-1);

	    //
	    // Return true to indicate that we've found the record.
	    //
	    return true;
	}
    }

    //
    // No record, return false.
    //
    return false;
}

//
// Add a record to the database with the provided key.
// Returns a pointer to the new record.
//
DBRecordData*
Database::add(long key)
{
    //
    // Add to the database.
    //
    records_.length(records_.length()+1);

    DBRecordData* data = new DBRecordData;

    //
    // Fill in the record data.
    //
    data -> key = key;
    data -> data = CORBA_string_dup("");

    records_[records_.length()-1] = data;

    return data;
}

//
// Find the record with the given key.  Returns a pointer to the
// database record, 0 otherwise.
//
DBRecordData*
Database::find(long key)
{
    for(CORBA_ULong i = 0; i < records_.length(); ++i)
    {
	if(records_[i] -> key == key)
	{
	    return records_[i];
	}
    }
    return 0;
}

//
// Return the record at position i.
//
DBRecordData*
Database::recordAt(CORBA_ULong i)
{
    return records_[i];
}

//
// Return the number of records in database.
//
CORBA_ULong
Database::size()
{
    return records_.length();
}
