// TableIDs.cpp : implementation file
//

#include "stdafx.h"
#include "DAO_Stock.h"
#include "TableIDs.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CTableIDs

IMPLEMENT_DYNAMIC(CTableIDs, CDaoRecordset)

CTableIDs::CTableIDs(CDaoDatabase* pdb)
	: CDaoRecordset(pdb)
{
	//{{AFX_FIELD_INIT(CTableIDs)
	m_Tablename = _T("");
	m_LastID = 0;
	m_nFields = 2;
	//}}AFX_FIELD_INIT
	m_nDefaultType = dbOpenDynaset;
}


CString CTableIDs::GetDefaultDBName()
{
	return _T("..\\PNStocks.mdb");}

CString CTableIDs::GetDefaultSQL()
{
	return _T("[TableIDs]");
}

void CTableIDs::DoFieldExchange(CDaoFieldExchange* pFX)
{
	//{{AFX_FIELD_MAP(CTableIDs)
	pFX->SetFieldType(CDaoFieldExchange::outputColumn);
	DFX_Text(pFX, _T("[Tablename]"), m_Tablename);
	DFX_Long(pFX, _T("[LastID]"), m_LastID);
	//}}AFX_FIELD_MAP
}

/////////////////////////////////////////////////////////////////////////////
// CTableIDs diagnostics

#ifdef _DEBUG
void CTableIDs::AssertValid() const
{
	CDaoRecordset::AssertValid();
}

void CTableIDs::Dump(CDumpContext& dc) const
{
	CDaoRecordset::Dump(dc);
}
#endif //_DEBUG

int CTableIDs::GetNextID(const char *Tablename)
{
	// This helper function will look up Tablename in the TableIDs table
	// in the database, and return the LastID field for that table, and add
	// 1 to that ID in the table.
	int NewID;

	// If already open, then close it
	if( IsOpen() )
		Close();

	// Set the filter to search the TableIDs table for a specific tablename
	m_strFilter.Format( " Tablename='%s' ", Tablename );

	// Open the query
	Open();
	
	// Was the Tablename found?
	if( IsEOF() )
	{
		// If not, insert the tablename, with an ID of 1
		AddNew();
		m_Tablename = Tablename;
		m_LastID=1;
	}
	else
	{
		// Otherwise, Just add 1 to the current ID
		Edit();
		m_LastID++;
	}
	
	NewID = m_LastID;
	// Save the new ID and/or record back to the table
	Update();

	// Return the new ID
	return( NewID );

}
