#ifndef __NT_DB_H__
#define __NT_DB_H__

#include <map>
#include <string>
#include "NTGlobals.h"


#ifdef WIN32

#include <windows.h>
#else
#include <stdio.h>
#endif
#include <sql.h>
#include <sqlext.h>

namespace NT {

class NTStmt;

class NTDb {
	static NTDb *global_dbconn;
public:
	NTDb();
	virtual ~NTDb();
	bool Connect( const char *username , const char *password , const char *database );

	NTStmt* Execute( std::string query );
	NTStmt* Execute( const char *query );
	void DirectExecute( std::string query );
	int ExecuteAndGetInteger( const char *query );
	int ExecuteAndGetInteger( std::string query );
	NTString ExecuteAndGetString( const char *query );
	NTString ExecuteAndGetString( std::string query );
	bool ExecuteAndGetBoolean( const char *query );
	bool ExecuteAndGetBoolean( std::string query );
	HDBC GetHDBC( void );
	HENV GetHENV( void );

	static void SetGlobalDBConn( NTDb *db );
	static NTDb *GetGlobalDBConn( void );
private:
	HENV henv;
	HDBC hdbc;
};

typedef struct _ntstmt_column {
	std::string colname;
	int coltype;
	int colsize;
	// now data related
	bool fetched;
	int indicator;
	int fetchsize;
	bool isset;
	void *data;
} NTStmtColumn;

class NTStmt {
public:
	NTStmt();
	NTStmt( NTDb *conn );
	virtual ~NTStmt();
	bool Bind( int numofcol , int type , void *buffer , int maxlen , int *index );
	bool Isset( std::string colname );
	bool Fetch( void );

	int GetInteger( int index , int *indicator = NULL );
	int GetInteger( std::string colname , int *indicator = NULL );

	std::string GetString( int index , int *indicator = NULL );
	std::string GetString( std::string colname , int *indicator = NULL );

	float GetFloat( int index , int *indicator = NULL );
	float GetFloat( std::string colname , int *indicator = NULL );

	double GetDouble( int index , int *indicator = NULL );
	double GetDouble( std::string colname , int *indicator = NULL );

	bool GetBoolean( int index , int *indicator = NULL );
	bool GetBoolean( std::string colname , int *indicator = NULL );

	HSTMT GetHSTMT( void ) { return hstmt; }
	void FetchRecordsetInfo( void );
	int GetIndexFromName( std::string colname );

protected:
	void FetchCol( unsigned int colnum );
	void FreeFetchedData( void );
	HSTMT hstmt;
	NTDb *dbconn;
	unsigned int numofresultcolumns;
	std::map<NTString, int> fieldnames;
	std::vector<NTStmtColumn> columns;
};

}


#endif

