// TableIDs.cpp : implementation file
//

#include "stdafx.h"
#include "ODBC_Stock.h"
#include "TableIDs.h"

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

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

IMPLEMENT_DYNAMIC(CTableIDs, CRecordset)

CTableIDs::CTableIDs(CDatabase* pdb)
	: CRecordset(pdb)
{
	//{{AFX_FIELD_INIT(CTableIDs)
	m_LastID = 0;
	m_Tablename = _T("");
	m_nFields = 2;
	//}}AFX_FIELD_INIT
	m_nDefaultType = snapshot;
}


CString CTableIDs::GetDefaultConnect()
{
	return _T("ODBC;DSN=PNStocks");
}

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

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

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

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

void CTableIDs::Dump(CDumpContext& dc) const
{
	CRecordset::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 );

}
