/*gcc y.c -L/isip/data/research/cavs/util/mysql/lib/mysql -lmysqlclient */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <signal.h>
#include <math.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include "flatfile.h"

//#include "/isip/data/research/cavs/util/mysql/include/mysql/mysql.h"
#include "mysql.h"

#define HOSTNAME "localhost"
#define USERNAME "dialog"
#define PASSWORD "pass123"

#define DATABASE_NAME "flatroute"

#if 0
Example compiling:
gcc -I/usr/local/mysql/include     campus.c  -L/usr/local/mysql/lib -lmysqlclient -lz -lcrypt -lm -o campus
Add on: "-g" for debug.

Example running:
./campus campus_ref.text

and the expected layout for this file is
=======begin
building: Agricultural Education Shop
name:   Not in Use
refname:  44 Lee Blvd
building: Aiken Village
name:   Married Student Housing - Apartments
refname:  1 Wallace Cir
building: Allen Hall
name:   Office of the President
refname:  1 Wallace Cir
=======end
#endif

int main(int argc,char* argv[]) {

  if (argc == 1) {
    printf("Usage: ./campus <file> "
	   "[username] [password] [host] [database]\n");
    printf("Note: If any of the optional user/pass/etc are given, they must "
	   "all be provided. So it is is either none or all\n");
    return 0;
  }
  
  MYSQL *myData;
  MYSQL_RES *res;
  MYSQL_ROW row;
  char SQLQuery[2048];
  int j,k,x;
  int exist;
  unsigned int num_fields;
  //unsigned int i;
  //MYSQL_FIELD *fields;

  int counter = 0;

  FILE *fid;
  char building[120];
  char name[120];
  //char city[120];
  //char telephone[120];
  //char distance[20];
  char refname[120];
  char line[120];
  char filename[256];
  //char buff [2000];

  int row_count = 0;
  row_count = 0;
  
  myData=mysql_init((MYSQL*)0);
  
  char *user = USERNAME;
  char *pass = PASSWORD;
  char *host = HOSTNAME;
  char *database = DATABASE_NAME;

  if (argc == 6) {
    user = argv[2];
    pass = argv[3];
    host = argv[4];
    database = argv[5];
  }
  
  if (mysql_real_connect
      (myData,
       //"isip221.isip.msstate.edu","gao","qaz1234","",0,NULL,0)) {
       //HOSTNAME, USERNAME, PASSWORD,"",0,NULL,0)) {
       host, user, pass, "", 0, NULL, 0)) {	 
	 //mysql_select_db(myData,"flatroute");
	 //mysql_select_db(myData,DATABASE_NAME);
	 mysql_select_db(myData, database); 
	 
	 printf("Successfully connected ... \n\n\n");
       }
  else {
    printf("Unable to connect....\n");
    exit(0);
  }

  // Check length of filename inputted
  //  
  if ((int)strlen(argv[1]) < (int)sizeof(filename)-1) {
    strcpy(filename, argv[1]);
  }
  else {
    printf("Filename too big for buffer!\n");
  }

  // Attempt to open it
  fid = fopen(filename,"rt");
  if (!fid){
    printf("Error opening file: %s\n", filename);
    fflush(stdout);
    return 0;
  }
  
  while(fgets(line,100,fid) != NULL) {
    // First line must be "building: stuff"
    if(strncmp(line,"building",8) != 0) {
      printf("%s", line); 
      exit(1);
    }

    get_flatfile_param(line, building, sizeof(building));

    // If no building then exit loop
    //
    if (strlen(building) == 0)
      break;
    //printf("****name***** [%s]\n", building);

    // Get next line, which should be "name:"
    fgets(line, 100, fid);
    get_flatfile_param(line, name, sizeof(name));

    // Get next line which should be "refname:"
    fgets(line, 100, fid);
    get_flatfile_param(line, refname, sizeof(refname));
   
    counter++;
    printf("counter=%d\n",counter);
    printf("[%s], [%s], [%s]\n", building, name, refname);

   /*--------------- insert row into SQL database -----------------*/
   
   if(strlen(name)>0) {
    
 
     sprintf (SQLQuery, "select * from campusname where building like "
	      "\"%s%%\" and name like \"%s%%\"", building, name);

     printf("%s\n", SQLQuery);

     x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
     //printf("x returned %i\n",x);
     // Returns 0 on successful so..
     if (x != 0) {
       printf("Error executing [%s]. Attempting next query\n", SQLQuery);
       continue;
     }
     res=mysql_store_result(myData);
     if (res == NULL) {
       printf("Error result set was null on query [%s]. Going to next query\n",
	      SQLQuery);
       continue;
     }

     if ((row=mysql_fetch_row(res)))
       exist = 1;
     else
       exist = 0;

     // Find number of fields
     num_fields = j = mysql_num_fields(res);
     /*
     num_fields = j;
     fields = mysql_fetch_fields(res);

     for(i = 0; i < num_fields; i++) {
       printf("Field %u is %s\n", i, fields[i].name);
     }
     
     printf("\n");
     */
     if(exist == 1) {     
       printf("Error found already at [");
       // Print out the data then
       do {
	 for(k=0;k<j;k++) {
	   if (row[k] != NULL)
	     printf("[%s],",row[k]);
	   }
	 printf("\n");
       }
       while ((row = mysql_fetch_row(res)));
     }
     else {   // no data existed so insert the data
       sprintf (SQLQuery,"INSERT INTO campusname (building, name, refname) "
		"VALUES('%s','%s', '%s')", building, name, refname);
       printf("[%s]\n", SQLQuery);
       x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
       if (x != 0) {
	 printf("Error There was a problem inserting data into database on\n");
	 printf("query [%s]\n",SQLQuery);
       }
       else {
	 row_count++;
	 printf("row inserted=%d\n",row_count);
       }
     }
   }
  }

  printf("total names in the files=%d\n",counter);
  printf("total names inserted to database=%d\n", row_count);
  fclose(fid);
  
  return 0;
}
