/*
 *
 * Much of this code was adopted from easysoft tutorials
 *   http://www.easysoft.com/developer/languages/c/odbc_tutorial.html
 *   http://www.easysoft.com/developer/languages/c/odbc-tutorial-fetching-results.html
 */

#include <string.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

/* This routine is taken from the easysoft tutorials */
void extract_error(
		   char *fn,
		   SQLHANDLE handle,
		   SQLSMALLINT type)
{
  SQLINTEGER i = 0;
  SQLINTEGER native;
  SQLCHAR state[ 7 ];
  SQLCHAR text[256];
  SQLSMALLINT len;
  SQLRETURN ret;

  fprintf(stderr,
            "\n"
            "The driver reported the following diagnostics whilst running "
	  "%s\n\n",
	  fn);

    do
      {
        ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
                            sizeof(text), &len );
        if (SQL_SUCCEEDED(ret))
	  printf("%s:%ld:%ld:%s\n", state, i, native, text);
      }
    while( ret == SQL_SUCCESS );
}


/* This is modification of the easysoft example */
int main(int argc, char *argv[]) {
  SQLHENV env;             /* Environment handle */
  SQLHDBC dbc;             /* Database connection */
  SQLHSTMT stmt;           /* Statement for execution */
  SQLRETURN ret;           /* ODBC API return status */
  SQLSMALLINT columns;     /* number of columns in result-set */
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;

  /* Allocate an environment handle */
  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
  /* We want ODBC 3 support */
  SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
  /* Allocate a connection handle */
  SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
  /* Connect to the DSN mydsn */
  /* You will need to change mydsn to one you have created and tested */
  ret = SQLDriverConnect(dbc, NULL, "DRIVER={MySQL};Server=joe.cs.unca.edu;Port=3306;Database=socialDB;UID=csci343;", SQL_NTS,
			 outstr, sizeof(outstr), &outstrlen,
			 SQL_DRIVER_COMPLETE);
  if (SQL_SUCCEEDED(ret)) {
    printf("Connected\n");
    printf("Returned connection string was:\n\t%s\n", outstr);
    if (ret == SQL_SUCCESS_WITH_INFO) {
      printf("Driver reported the following diagnostics\n");
      extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
    }
  } else {
    fprintf(stderr, "Failed to connect\n");
    extract_error("SQLDriverConnect", dbc, SQL_HANDLE_DBC);
  }
  /*
  SQLConnect(dbc,
	     (SQLCHAR *)"DRIVER={MySQL};Server=joe.cs.unca.edu;Port=3306;Database=socialDB", SQL_NTS,
	     (SQLCHAR *)"csci343", SQL_NTS,
	     (SQLCHAR *)"", SQL_NTS) ;
  */
  /* Allocate a statement handle */
  SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
  /* Retrieve a list of tables */
  // ret =  SQLTables(stmt, NULL, 0, NULL, 0, NULL, 0, "TABLE", SQL_NTS);
  ret = SQLPrepare(stmt, "SELECT A.name, B.name "
		   "FROM Highschooler A, Highschooler B, Friend F "
		   "WHERE A.ID = F.ID1 AND B.ID = F.ID2 AND A.name < B.name ;",
		   SQL_NTS) ;
  if (SQL_SUCCEEDED(ret)) {
    printf("Prepared\n");
  } else {
    fprintf(stderr, "Failed to prepare\n");
    extract_error("SQLDprepare", dbc, SQL_HANDLE_DBC);
  }
  ret = SQLExecute(stmt) ;
  /* How many columns are there */
  SQLNumResultCols(stmt, &columns);
  printf("number of columns is %d\n", columns) ;
  /* Loop through the rows in the result-set */
  while (SQL_SUCCEEDED(ret = SQLFetch(stmt))) {
    SQLUSMALLINT i;
    if (SQL_SUCCEEDED(ret)) {
      printf("Fetched\n");
    } else {
      fprintf(stderr, "No fetch\n");
      extract_error("SQLFetch", dbc, SQL_HANDLE_DBC);
    }
    printf("Row %d\n", row++);
    /* Loop through the columns */
    for (i = 1; i <= columns; i++) {
      // SQLINTEGER indicator;
      SQLLEN indicator;
      char buf[512];
      /* retrieve column data as a string */
      ret = SQLGetData(stmt, i, SQL_C_CHAR,
		       buf, sizeof(buf), &indicator);
      if (SQL_SUCCEEDED(ret)) {
	/* Handle null columns */
	if (indicator == SQL_NULL_DATA) strcpy(buf, "NULL");
	printf("  Column %u : %s\n", i, buf);
      }
    }
  }
  if (SQL_SUCCEEDED(ret)) {
    printf("Fetched\n");
  } else {
    fprintf(stderr, "No fetch\n");
    extract_error("SQLFetch", dbc, SQL_HANDLE_DBC);
  }
}
