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

Example running:
./campus_direction campus_direction_1.text 
./campus_direction campus_direction_2.text 

and the expected layout for this file is
=======begin
start_name        MSU/NSF Engineering Research Center
start_add          
start_interest     
start_city        Starkville
start_state       MS
start_zip          
end_name          Diagnostic Instrumentation and Analysis Laboratory
end_add            
end_interest       
end_city          Starkville
end_state         MS
end_zip            
total_distance    0.49
total_time         
directions        2
Turn right onto Joe Baddley Dr, Travel on Joe Baddley Dr 
0.27
Turn right onto Research Blvd, Travel on Research Blvd 
0.22
====end
#endif

  //void get_flatfile_param(char *, char *, int);

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

  if (argc == 1) {
    printf("Usage: ./campus_direction <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];
  MYSQL_FIELD *fields;

  int x = 0, exist = 0;
  int starting = 0, ending = 0, index=0;
  int num_fields, i, k, j, m;
  //int counter = 0;
  int  i_direction=0, start_point, len, row_count=0;
  FILE *fid;

  char start_name[70], start_add[70], start_interest[70], start_city[70], 
        start_state[70], start_zip[70];
  char end_name[70], end_add[70], end_interest[70], end_city[70], 
        end_state[70],  end_zip[70];
  char from[70], to[70], distance[70], time[70], direction[70];

  char line[200], directions[2000];

  myData=mysql_init((MYSQL*)0);

  char *user = USERNAME;
  char *pass = PASSWORD;
  char *host = HOSTNAME;
  char *database = DATABASE_NAME;

  if (argc != 2 && argc != 6) { 
    printf("Incorrect # of parameters in command line\n"); 
    fflush(stdout);
  }

  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("Succesfully connected ... \n\n\n");
       }
  else {
    printf("Unable to connect....\n");
    exit(0);
  }

  fid = fopen(argv[1], "rt");
  if (fid==NULL){
    printf("Error opening input file: %s\n", argv[1]); 
    fflush(stdout);
    return 0;
  }

  while(fgets(line,100,fid) != NULL) {

    printf("****line========***** [%s]\n", line);
    get_flatfile_param(line, start_name, sizeof(start_name));
    printf("****from***** [%s]\n", start_name);

    fgets(line, 100, fid);   
    get_flatfile_param(line, start_add, sizeof(start_add));

    fgets(line, 100, fid);    
    get_flatfile_param(line, start_interest, sizeof(start_interest));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, start_city, sizeof(start_city));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, start_state, sizeof(start_state));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, start_zip, sizeof(start_zip));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_name, sizeof(end_name));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_add, sizeof(end_add));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_interest, sizeof(end_interest));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_city, sizeof(end_city));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_state, sizeof(end_state));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, end_zip, sizeof(end_zip));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, distance, sizeof(distance));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, time, sizeof(time));
    
    fgets(line, 100, fid);    
    get_flatfile_param(line, direction, sizeof(direction));

    i_direction = atoi(direction);
    printf(" number of directions [%d]\n", i_direction);

    start_point = 1;

    for (m=0; m< i_direction; m++) {
      fgets(line, 200, fid);

      index=m+1;
      len = strlen(line);
      line[strlen(line)-1] = '\0';

      printf(" start_point-pre [%d]\n", start_point);
      printf(" len=****i= [%d][%d]\n", len, m);
      printf(" lines [%s]\n", line);
      strcpy(directions, line);
      printf(" directions-post [%s]\n", directions);

      start_point = strlen(directions);
      printf(" start_point [%d]\n", start_point);

      printf(" from [%s] to [%s] distance [%s] estimated time[%s]\n",
	       from, to, distance, time);
      printf(" directions [%s]\n",directions);

      fgets(line, 200, fid);

      len = strlen(line);
      line[strlen(line)-1] = '\0';

/*--------------- insert row into SQL database -----------------*/

      sprintf (SQLQuery,"select * from place where name like \"%s%%\" and city like \"%s%%\" and state like \"%s%%\" and zip like \"%s%%\"", start_name, start_city, start_state, start_zip);
  
      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");
	}
      }
      else {   /* no data exist, insert the data*/
	sprintf (SQLQuery,"INSERT INTO place (name, address, city, state, zip) VALUES(\"%s\",\"%s\", \"%s\",\"%s\", \"%s\") ", start_name, start_add, start_city, start_state, start_zip);
	printf("[%s]", SQLQuery);
	x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
	row_count++;
	printf("row inserted=%d\n",row_count);
      }
    
      sprintf (SQLQuery,"select * from place where name like \"%s%%\" and city like \"%s%%\" and state like \"%s%%\" and zip like \"%s%%\"", end_name, end_city, end_state, end_zip);
  
      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");
	}
      }
      else {   /* no data exist, insert the data*/
	sprintf (SQLQuery,"INSERT INTO place (name, address, city, state, zip) VALUES(\"%s\",\"%s\",\"%s\", \"%s\", \"%s\") ", end_name, end_add, end_city, end_state, end_zip);
	printf("[%s]", SQLQuery);
	x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
	row_count++;
	printf("row inserted=%d\n",row_count);
      }
  
// get the starting place id just inserted or already existing in the table

      sprintf (SQLQuery,"select id from place where name like \"%s%%\" and city like \"%s%%\" and state like \"%s%%\" and zip like \"%s%%\"", start_name, start_city, start_state, start_zip);
  
      printf("%s\n", SQLQuery);
  
      x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      res=mysql_store_result(myData);
  
      if ((row=mysql_fetch_row(res)))
	starting = atoi(row[0]);
  
      printf("starting place=%d\n", starting);
  
// get the end place id just inserted or already existing in the table

      sprintf (SQLQuery,"select id from place where name like \"%s%%\" and city like \"%s%%\" and state like \"%s%%\" and zip like \"%s%%\"", end_name, end_city, end_state, end_zip);
  
      printf("%s\n", SQLQuery);
  
      x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
      res=mysql_store_result(myData);
  
      if ((row=mysql_fetch_row(res)))
	ending = atoi(row[0]);

      printf("end place=%d\n", ending);

// test if the route already exists in the table

      sprintf (SQLQuery,"select * from route where sid ='%d' and did = '%d' and routeindex = '%d'", starting, ending, index);

      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 { //no data exist, insert the data
	sprintf (SQLQuery,"INSERT INTO route (sid, did, routeindex, distance, totaldistance, time, directions) VALUES('%d', '%d', '%d', '%s', '%s', '%s', '%s')", starting, ending, index, line, distance, time, directions);
	x=mysql_real_query(myData, SQLQuery, strlen(SQLQuery));
	row_count++;
	printf("row inserted=%d\n",row_count);
      }
    }
  }

  fclose(fid);

  printf("Closing mysql...\n");
  

  fprintf(stderr,"\nThe number of rows inserted -> %d\n\n",row_count);
  return 0;
}
