/*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 <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 address.c  -L/usr/local/mysql/lib -lmysqlclient -lz -lcrypt -lm -o address
Add on: "-g" for debug.

For external "flatfile.c" file:
gcc -I/usr/local/mysql/include flatfile.c address.c -L/usr/local/mysql/lib -lmysqlclient -lz -lcrypt -lm -o address
Add on: "-g" for debug.

Example running:
./address starkville_address.text
./address campus_address.text
./address building_add.text

and the expected layout for these files are:
=====begin
name            MSU/NSF Engineering Research Center
address         Joe Baddley Dr
city            Mississippi State
state           MS
telephone        
miles            
name            Diagnostic Instrumentation and Analysis Laboratory
address         Research Blvd
city            Mississippi State
state           MS
miles            
====end
#endif

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

  if (argc == 1) {
    printf("Usage: ./address <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,x;
  int exist;
  unsigned int num_fields;
  //unsigned int i;
  MYSQL_FIELD *fields;

  int counter = 0;

  FILE *fid;
  char name[120], address[120], city[120], state[120], telephone[120], distance[20];
  //int  i_direction, start_point, len;
  int row_count;
  char line[100];
  //char directions[120];
  char filename[256];
  //char buff [2000];

  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);
  }
  
  strcpy(filename, argv[1]);
  
  fid = fopen(filename,"rt");
  if (fid==NULL){
    fprintf(stderr, "Error opening file: %s\n", filename);
    fflush(stderr);
    return 0;
  }
  
  while(fgets(line,100,fid) != NULL) {
    if(line[0] !='n') {printf("%s", line); exit(1);} 
   get_flatfile_param(line, name, sizeof(name));
   if (strlen(name) == 0) break;
   printf("****name***** [%s]\n", name);
   fgets(line, 100, fid);   get_flatfile_param(line, address, sizeof(address));
   fgets(line, 100, fid);   get_flatfile_param(line, city, sizeof(city));
   fgets(line, 100, fid);   get_flatfile_param(line, state, sizeof(state));
   fgets(line, 100, fid);   get_flatfile_param(line, telephone, 
					       sizeof(telephone));
   fgets(line, 100, fid);   get_flatfile_param(line, distance, 
					       sizeof(distance));
   
   counter++;
   printf("counter=%d\n",counter);
   printf("[%s] [%s] [%s] [%s] [%s] [%s]\n", name, address, city,
	  state, telephone, distance);

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

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

     x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
     res=mysql_store_result(myData);

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

     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) {     
       /*for(k=0;k<j;k++)
	 {
	   if(row[k] !=NULL)
	     printf(" %s\n",row[k]);
	   else
	     printf("field %d is NULL\n",k);
	   
	     }
       while ((row = mysql_fetch_row(res))) {
	 for(k=0;k<j;k++)
	   {
	     if(row[k] !=NULL)
	       printf(" %s ",row[k]);
	     else
	       printf("field %d is NULL\n",k);
	   }
	 printf("\n");
       }
       */
       // do nothing
     }
     else {   /* no data exist, insert the data*/
       sprintf (SQLQuery,"INSERT INTO address (name, address, city, state, "
		"telephone, distance) VALUES('%s','%s','%s','%s','%s','%s')",
		name, address, city, state, telephone, distance);
       printf("[%s]", SQLQuery);
       x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
       if (x != 0) {
	 fprintf(stderr, "ERROR with query [%s]\n", SQLQuery);
	 fflush(stderr);
       }
       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);
  fprintf(stderr,"total names in the files=%d\n",counter);
  fprintf(stderr,"total names inserted to database=%d\n", row_count);
  fclose(fid);
  
  return 0;
}





