#include "query_user.h"

#include <stdexcept>
#include <ocilib.h>
#include "../../db/ocilib/db_oper.h"
#include "../Datastructure/UserInfo/UserInfo.h"
#include <ocilib.hpp>

using namespace std;

UserInfo queryUserInfo( const string & userName,
                        const string & password,
                        const string & tnsName,
                        const string & staffP13 )
{
	OCI_Connection * pConn      = nullptr;
	OCI_Statement *  pStmt      = nullptr;
	OCI_Resultset *  pResult    = nullptr;
	int              returnCode = 0;


	string sqlQueryStaff =
			"SELECT a.staff_p13, a.staff_name, b.staff_post \n"
			"FROM staff_info a, \n"
			"staff_post_code b \n"
			"WHERE a.staff_post_code = b.staff_post_code \n"
			"AND a.staff_p13 = :p13";

	returnCode = OCI_Initialize( l_error_handler, nullptr, OCI_ENV_DEFAULT );

	if ( static_cast<bool>(returnCode) == false )
	{
		string errorMessage( "ocilib初始化错误:" );
		errorMessage.append( get_last_error_message() );

		throw runtime_error( errorMessage );
	}

	try
	{
		pConn = OCI_ConnectionCreate( tnsName.c_str(),
		                              userName.c_str(),
		                              password.c_str(),
		                              OCI_SESSION_DEFAULT );
	}
	catch ( runtime_error & error )
	{
		OCI_Cleanup();

		throw error;
	}

	try
	{
		pStmt = OCI_StatementCreate( pConn );

		OCI_Prepare(pStmt, sqlQueryStaff.c_str());
		OCI_AllowRebinding( pStmt, true );
		OCI_BindString( pStmt, ":p13", const_cast<otext*>(staffP13.c_str()), staffP13.size() );
		
		OCI_Execute( pStmt );
		
		pResult = OCI_GetResultset( pStmt );

		//检查结果集，如果没有返回，则说明没有此用户	
		if ( OCI_FetchNext( pResult ) == false )
		{
			throw runtime_error( "用户不存在！" );
		}
	}
	catch ( runtime_error & error )
	{
		OCI_ConnectionFree( pConn );
		OCI_Cleanup();

		throw error;
	}

	UserInfo info( OCI_GetString( pResult, 1 ),
	               OCI_GetString( pResult, 2 ),
	               OCI_GetString( pResult, 3 ) );

	OCI_ConnectionFree(pConn);
	OCI_Cleanup();

	return info;
}
