#include "monitor.h"

char rbuf[BUFSIZE];
char buf[BUFSIZE];

main(int argc, char *argv[]) {
  int   sd;
  struct  sockaddr_in server,from,addr;
  struct  hostent *hp, *gethostbyname();
  int fromlen, cc;
  char ThisHost[MAXHOSTNAME];
  char str[INET_ADDRSTRLEN];

  //Verificamos la sintaxis
  if (argc != 3) {
    printf("Usar: monitor <servidor_acumulador> <puerto_monitor>\n");
    exit(1);
  }

  //Le podemos pasar el host o la ip
  if  ( (hp = gethostbyname(argv[1])) == NULL ) { //Intentamos con el host de argumento
    addr.sin_addr.s_addr = inet_addr(argv[1]); //no funciono, ahora buscamos por IP de argumento
    if ((hp = gethostbyaddr((void *)&addr.sin_addr.s_addr, sizeof(addr.sin_addr.s_addr),AF_INET)) == NULL) {
      fprintf(stderr, "Can't find host %s\n", argv[1]);
      exit(-1);
    }
  }
  //Ahora rellenamos la direccion del server.
  bcopy (hp->h_addr, &(server.sin_addr), hp->h_length);
  server.sin_family = AF_INET;
  server.sin_port = htons(atoi(argv[2]));

  //Creamos socket
  sd = socket (AF_INET,SOCK_STREAM,0);
  if (sd<0) {
    perror("opening stream socket");
    exit(-1);
  }

  /* Connect to TCP/SERVER */
  if ( connect(sd, (struct sockaddr *)&server, sizeof(server) ) < 0) {  
    close(sd);
    perror("connecting stream socket");
    exit(0);
  }

  //Asociamos la informacion asociada al socket para poder acceder a ella 
  //'from' adquiere la informacion del servidor.
  fromlen = sizeof(from);
  if (getpeername(sd, (struct sockaddr *)&from,&fromlen)<0){
    perror("could't get peername\n");
    exit(1);
  }
  //Guarda en hp la informacion asociada a from para acceder a ella.
  if ((hp = gethostbyaddr((void *)&from.sin_addr.s_addr, sizeof(from.sin_addr.s_addr),AF_INET)) == NULL)
    fprintf(stderr, "Can't find host %s\n", str);

  printf("Connected to TCP/Server: ");
  inet_ntop(AF_INET, &(from.sin_addr),str,INET_ADDRSTRLEN);
  printf("%s (%s:%d)\n", hp->h_name, str, ntohs(from.sin_port));

  //Nos preparamos a recibir la informacion del servidor
  cleanup(rbuf);
  sprintf(buf,"monitor"); 
  //Se envia la pide la informacion de las votaciones
  if (send(sd, buf, sizeof(buf), 0) <0 )
    perror("sending stream message");
  //Se guarda la data recibida en rbuf
  while(1) {
    if ((cc=recv(sd, rbuf, sizeof(rbuf), 0)) < 0)
      perror("receiving echo");
    if (strcmp(rbuf, "done") == 0)
      break; //terminamos de adquirir la informacion
    printf("%s",rbuf);
  }
  printf ("\n\n");
  close(sd);//Cerramos la conexion y salimos
  exit (0);
}

void cleanup(char *buf) {
  int i;
  for(i=0; i<BUFSIZE; i++) buf[i]='\0';
}
