#include <stdio.h>          
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>	/* exit() necesita esta cabecera */
#include <arpa/inet.h>  /* inet_ntoa() necesita esta cabecera */
#include <netdb.h>   /* gethostbyname() necesita esta cabecera */
#include <unistd.h>    /* contains read/write */
#include <fcntl.h>
#include <ctype.h>
#include <pthread.h>        /* for POSIX threads */
#include <libpq-fe.h>


#define PORT 3355 /* El puerto que será abierto */
#define MAX_CON 2 /* El número de conexiones permitidas */
#define MAXDATASIZE 100   

/* El número máximo de datos en bytes */


void *ThreadMain(void *arg);            /* Main program of a thread */

struct sockaddr_in server; 
   /* para la información de la dirección del servidor */

struct sockaddr_in client; 
   /* para la información de la dirección del cliente */

/* Structure of arguments to pass to client thread */
struct ThreadArgs
{
    int fd2;                      /* Socket descriptor for client */
};

/* ***************************************************************************************** */
int exit_nicely(PGconn *conn)
{
    PQfinish(conn);
    exit(1);
    return (0);
}

int ejecutar(char *query, int fd2, char *db)
{
    char       *pghost,
    	       *pgport,
    	       *pgoptions,
    	       *pgtty,
    	       *dbName,
              	*pguser;
    int         nFields;
    int         i,j;

    PGconn     *conn;
    PGresult   *res;
    PGnotify   *notify;//*threadArgs

	pghost = NULL;
	pgport = NULL; 
	pgoptions = NULL; 
 	pgtty = NULL; 
	

	conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbName=db);

   if (PQstatus(conn) == CONNECTION_BAD)
    {
        fprintf(stderr, "Connection to database '%s' failed.\n", dbName=db);
        fprintf(stderr, "%s", PQerrorMessage(conn));
        return (exit_nicely(conn));
    }
    else
    	{
           printf("Conexión con Postgres exitosa");
	} 	
	res = PQexec(conn, query);
	if(res==NULL) {
		fprintf(stderr, "Error: res==NULL\n");
		fprintf(stderr, "Query: %s\n\n", query);
		PQclear(res);
		return(exit_nicely(1));		
	}
	if(PQresultStatus(res)!=PGRES_COMMAND_OK) {
		fprintf(stderr, "Error: %d\n", PQresultStatus(res));
		fprintf(stderr, "Query: %s\n\n", query);
		PQclear(res);
		return(exit_nicely(1));
	}
        else{
		return(3);

	}
	
     	if ((send(fd2,res,MAXDATASIZE,0))==-1)   
		printf("error mandando respuesta al usuario"); 
	
    	printf("AL CLEINTE SE LE ENVIO %s",res); 	
	PQfinish(conn);
	return (1);
}

/* ***************************************************************************************** */



int main()
{

   int fd, fd2,clntSock,res; /* los ficheros descriptores */
   int sin_size;
   void *thread_result;
   pthread_t threadID;              /* Thread ID from pthread_create() */
   struct ThreadArgs *threadArgs;   /* Pointer to argument structure for thread */
   /* A continuación la llamada a socket() */
   if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {  
      printf("error en socket()\n");
      exit(-1);
   }

   server.sin_family = AF_INET;         
   server.sin_port = htons(PORT); 
      //server.sin_addr.s_addr = "localhost"; 
   server.sin_addr.s_addr = INADDR_ANY; 
    //INADDR_ANY coloca la dirección IP automáticamente 
   bzero(&(server.sin_zero),8); 
   /* escribimos ceros en el reto de la estructura */

   /* A continuación la llamada a bind() */
   if(bind(fd,(struct sockaddr*)&server,
           sizeof(struct sockaddr))==-1) {
      printf("error en bind()\n");
      exit(-1);
   }     

   if(listen(fd,MAX_CON) == -1) {  /* llamada a listen() */
      printf("error en listen()\n");
      exit(-1);
   }

   while(1) {
      sin_size=sizeof(struct sockaddr_in);
      /* A continuación la llamada a accept() */
      if ((fd2 = accept(fd,(struct sockaddr *)&client,
                        &sin_size))==-1) {
        printf("error en accept()\n");
       exit(-1);}

        /* Create separate memory for client argument */
        if ((threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs))) 
               == NULL)
            printf("malloc() failed");
        threadArgs -> fd2 = fd2;

        /* Create client thread */
        if (pthread_create(&threadID, NULL, ThreadMain, (void *) threadArgs) != 0)
            printf("pthread_create() failed");
        printf("with thread %ld\n", (long int) threadID);
       /* res=pthread_join(threadID,&thread_result);
	if (res != 0) {
		perror("Thread join failed");
		exit(EXIT_FAILURE);
		}  */
      } //fin del while

}  // fin del main





void *ThreadMain(void *threadArgs)
{
    int clntSock,fd2,fd1;     /* Socket descriptor for client connection */
    char buf[MAXDATASIZE], db[MAXDATASIZE];  /* en donde es almacenará el texto recibido */
    int numbytes,i,respuesta;
    db="OLIMPO";
	  /* Guarantees that thread resources are deallocated upon return se libera la memoria eliminando el hilo */
    pthread_detach(pthread_self()); 

    /* Extract socket file descriptor from argument */
    fd2 = ((struct ThreadArgs *) threadArgs) -> fd2;
    free(threadArgs);              /* Deallocate memory for argument */

     printf("Se obtuvo una conexión desde %s\n",
             inet_ntoa(client.sin_addr) ); 
      /* que mostrará la IP del cliente */

      send(fd2,"Bienvenido a mi servidor.\n",22,0); 
      /* que enviará el mensaje de bienvenida al cliente */

        numbytes=recv(fd2,buf,MAXDATASIZE,0);
        buf[numbytes]='\0';
/* *************************************************************** */	
	respuesta = ejecutar(buf,fd2,db);
	if (respuesta == 3){
		strcpy(buf,"No se realizó la tarea con exito");
		pthread_exit("fallo la ejecucion");
	}
	else
		strcpy(buf,"La tarea se realizo con �ito");
       if ((send(fd2,buf,MAXDATASIZE,0))==-1)
		printf("Respuesta NO Enviada"); 

       	printf("Respuesta Enviada ********"); 


/* *************************************************************** */ 
       

        close(fd2); /* cierra fd2 */
 //return (0);	

    return (NULL);
}// fin de la funciondel hilo
