// file: $isip/util/demo/isip_comm_server_dialog_database/mysql_interface.cc
// version: $Id: mysql_interface.cc 10572 2006-06-26 21:54:34Z rei5 $
//

#include "mysql_interface.h"
#include "isip_comm_dialog_navigation_db.h"

// These two variables are in isip_comm_dialog_navigation_db_globals.cc
// and extern'd in isip_comm_dialog_navigation_db.h
//
//extern char rowbuf[];
//extern char rowhead[];

#define MYSQL_CONNECTION_TIMEOUT   10

int g_row_count;

MYSQL *g_myData;
MYSQL_RES *g_res;
MYSQL_ROW g_row;
char g_SQLQuery[2048];
unsigned int g_num_fields;
MYSQL_FIELD *g_fields;

/************************************************************************
 * sql_connect()
************************************************************************/

// Uses global variables to connect
//
void sql_connect() {
  
  char new_id[1000];

  // make sure we don't have one open right now
  //
  mysql_close(g_myData);
    
  g_myData = mysql_init((MYSQL*)0);
  if (g_myData == NULL) {
    printf("Unable to allocate a MYSQL handle in sql_connect, exiting\n");
    exit(0);
  }

  // Set connection-timeout
  //
  unsigned int mysql_timeout_sec = MYSQL_CONNECTION_TIMEOUT;
  if (mysql_options(g_myData, MYSQL_OPT_CONNECT_TIMEOUT,
		    (char*)&mysql_timeout_sec)) {
    printf("Unable to set timeout to be [%u] seconds\n", mysql_timeout_sec);
  }
  //printf("Connecting to host [%s] with user [%s] "
  // "and pass begins with [%c]\n",
  // MY_HOST, MY_USER, MY_PASSWORD[0]);
  printf("Connecting to host [%s] with user [%s] "
	 "and pass begins with [%c]\n",
	 db_host, db_username, db_password[0]);

  //if (mysql_real_connect(g_myData, MY_HOST, MY_USER, MY_PASSWORD,"",
  //			 0, "",0)) {
  //if (mysql_select_db(g_myData, MY_DATABASE) != 0) {
  //   printf("Unable to select table %s\n", MY_DATABASE);
  //  fflush(stdout);
  //  exit(0);
  //}
  if (mysql_real_connect(g_myData, db_host, db_username, db_password,"",
			 0, "",0)) {
    if (mysql_select_db(g_myData, db_database) != 0) {
      printf("Unable to select database named [%s]\n", db_database);
      sql_disconnect();      
      fflush(stdout);
      exit(0);
    }
    printf("Successfully connected to [%s:%s]... \n\n\n",
	   db_host, db_database);
  }

  else {
    printf("Unable to connect to [%s] .... in sql_connect\n", db_host);
    strcpy(new_id, mysql_get_client_info()); 
    printf("Failed to connect to database:\n   "
	   "Client Info: [%s]\n   Error: [%s]\n",
	   new_id,
	   mysql_error(g_myData));
    
    fflush(stdout);
    exit(0);
  }
  
  fflush(stdout);
}

/************************************************************************
 * sql_disconnect()
 ************************************************************************/
void sql_disconnect(void) {
  
  printf("Closing Database Connection (may take a minute, hold on) ...");
  fflush(stdout);

  mysql_close(g_myData);
  
  printf("Disconnected\n");
  fflush(stdout);
}

// This function will return this globally open MYSQL connection
// The variables at the top are not accessible through variable names
// throughout the rest of the files so this allows this file to act
// as a class and have a "get" method for it.
//
MYSQL* get_sql_connection(void) {
  return g_myData;
}
  

// The point of this function is to store the result of the query in
// the global variable of "g_res" and also "g_num_fields" and "g_fields"
//
// Returns 1 on success, -1 on fail
int do_sql_query(char* str) {
  
  int x;

  // Check for null pointer
  //
  if (!str) {
    printf("str passed into query_address is NULL!\n");
    return -1;
  }

  // Reset some global variables
  //
  g_row_count = 0;
  rowbuf[0] = 0;
  
  printf("do_sql_query command:[%s]\n", str);
  
  //--------------- query from SQL database -----------------
  
  if (strlen(str) > 0) {
    
    strcpy(g_SQLQuery, str);
    
    printf("do_sql_query query:[%s]\n", g_SQLQuery);
    fflush(stdout);

    printf("before mysql_real_query do_sql_query query:[%s]\n", g_SQLQuery);
     fflush(stdout);
    x = mysql_real_query(g_myData, g_SQLQuery, strlen(g_SQLQuery));

    
    printf("after mysql_real_query do_sql_query query:[%s]\n", g_SQLQuery);
    fflush(stdout);

    // x == 0 is successful return
    //
    if (x != 0) {
      printf("do_sql_query failed on mysql_real_query\n");
      return -1;
    }
    
    g_res = mysql_store_result(g_myData);

    printf("after mysql_store_result do_sql_query query:[%s]\n", g_SQLQuery);
    // g_res != NULL is successful return
    //
    if (g_res == NULL) {
      printf("do_sql_query failed on mysql_store_result\n");
      return -1;
    }
    
    // Get total number of fields
    //
    g_num_fields = mysql_num_fields(g_res);

    printf("after mysql_num_fields do_sql_query query:[%s]\n", g_SQLQuery);
    
    // Get the fields to the global fields structure
    //
    g_fields = mysql_fetch_fields(g_res);

    printf("after mysql_fetch_fields do_sql_query query:[%s]\n", g_SQLQuery);
    //debug begin
    for (unsigned int i = 0; i < g_num_fields; i++) {
      printf("do_sql_query(): Field %u is %s\n", i, g_fields[i].name);
    }
    printf("\n");
    //debug end
  }
  // else the strlen(str) is <= 0
  else {
    printf("the string passed to do_sql_query is empty!\n");
  }
 
  fflush(stdout);

  return 1;
}


void fetch_header(char *str) {
  head_row_into_string(str);
}

//************************************************************************
// * Stuff for printing and formatting rows. No more SQL calls.
// ***********************************************************************
// No failing returns, will take the values in g_fields and put into a single
// string such as
// input: fields[0] = "bob", fields[1] = "joe", fields[2] = "susan"
// output: "( bob joe susan )"
void head_row_into_string(char *str) {

   unsigned int i;
   *str = 0;
   strcat(str,"( ");

   for (i = 0; i < g_num_fields; i++) {
     //debug
     printf("head_row_into_string(): Field %u is %s\n", i, g_fields[i].name);
     //debug end
     
     strcat(str, g_fields[i].name);
     strcat(str," ");
   }
   strcat(str,")");
}

// This function creates a string in the parameter char array that
// contains all of the returned columns like 
// Values[one,two,three] ==> String["one" "two" "three" ] eg "\"one\" \"two\""
//
// returns >0 on success to show number of columns
// returns -1 on fail

int fetch_row(char *str) {
  
  int k;

  str[0] = '\0';

  // Find out how many columns
  //
  int l_num_fields = mysql_num_fields(g_res);

  // Get the columns
  //
  g_row = mysql_fetch_row(g_res);
  g_row_count = 0;

  // And place in like
  // ["one" "two" "three" ]
  // from brace to brace; not including the braces
  //
  if (g_row) {
    for (k = 0; k < l_num_fields; k++) {
      //debug
      //printf(" %s ", g_row[k]);
      
      strcat(str,"\"");
      strcat(str, g_row[k]);
      strcat(str,"\" ");	
    }
    
    g_row_count++;
    return g_row_count;

  }

  // else return error code
  return (-1);
}

