#include <stdio.h>
#include <stdlib.h>

#include "common.h"

// connect with explicitly specified connection string
// useful when testing with multiple different installed drivers
// (of course, other than the hardcoded DSN would do also)
void
test_connect_exp(char *constr)
{
	SQLRETURN ret;
	SQLCHAR str[1024];
	SQLSMALLINT strl;
	SQLCHAR dsn[1024];

	snprintf(dsn, sizeof(dsn), constr);

	SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);

	SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

	SQLAllocHandle(SQL_HANDLE_DBC, env, &conn);
	ret = SQLDriverConnect(conn, NULL, dsn, SQL_NTS,
						   str, sizeof(str), &strl,
						   SQL_DRIVER_COMPLETE);
	if (SQL_SUCCEEDED(ret)) {
		printf("connected\n");
	} else {
		print_diag("SQLDriverConnect failed.", SQL_HANDLE_DBC, conn);
		exit(1);
	}
}

int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	char param1[20] = { 1, 2, 3, 4, 5, 6, 7, 8 };
	char param2[20] = { 1, 2, 3, 4, 5, 6, 7, 8 };
	SQLLEN cbParam1;
	SQLLEN cbParam2;

	if(argc > 1)
	{
		printf("Using connection string \"%s\"\n", argv[1]);
		test_connect_exp(argv[1]);
	}
	else
	{
		test_connect();
	}

	rc = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/* Create a test function with one IN and one OUT parameter */
	rc = SQLExecDirect
	(
		hstmt
		, (SQLCHAR *)
		"CREATE OR REPLACE FUNCTION fout ( IN ival INTEGER, OUT oval INTEGER ) RETURNS INTEGER AS $$"
		" BEGIN"
		"  oval := -ival;"
		" END;"
		"$$ LANGUAGE plpgsql;"
		, SQL_NTS
	);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed while creating function", hstmt);


	/*** Test SQLBindParameter with SQLExecDirect ***/
	printf("\nTesting SQLBindParameter (IN and OUT) with SQLExecDirect...\n");

	/* bind param  */
	strcpy(param1, "1");
	cbParam1 = SQL_NTS;
	rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
						  SQL_C_CHAR,	/* value type */
						  SQL_INTEGER,	/* param type */
						  20,			/* column size */
						  0,			/* dec digits */
						  param1,		/* param value ptr */
						  0,			/* buffer len */
						  &cbParam1		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	cbParam2 = SQL_NULL_DATA;
	rc = SQLBindParameter(hstmt, 2, SQL_PARAM_OUTPUT,
						  SQL_C_CHAR,	/* value type */
						  SQL_INTEGER,	/* param type */
						  20,			/* column size */
						  0,			/* dec digits */
						  param2,		/* param value ptr */
						  0,			/* buffer len */
						  &cbParam2		/* StrLen_or_IndPtr */);
	CHECK_STMT_RESULT(rc, "SQLBindParameter failed", hstmt);

	rc = SQLExecDirect(hstmt, (SQLCHAR *) "{ CALL fout (?,?) }", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);


	/* Clean up */
	test_disconnect();

	return 0;
}
