#include <stdio.h>
#include <netinet/in.h>
#include <signal.h>
#include <netdb.h>
#include <errno.h>
#include <ncurses/ncurses.h>
#include <strings.h>
#include <pthread.h>

int sock;
char pseudo[128], couleur[9];
WINDOW *bas, *haut;

void *envoi(void *num)
{
char chaine[128], lu[128];
int i;

  while (1)
  {
    wgetstr(bas, lu);
    strcpy(chaine, pseudo);
    strcat(chaine, "> ");
    strcat(chaine, lu);
    strcpy(lu, chaine);
    wprintw(haut, "%s\n", lu);
    wrefresh(haut);

    strcpy(chaine, couleur);
    strcat(chaine, lu);
    strcat(chaine, "\x0d\x0A");
    if (write(sock, chaine, strlen(chaine))==-1)
      perror("Envoi foiré");
    wclear(bas);
    wmove(bas, 0, 0);
    wrefresh(bas);
  }
}

void *reception(void *num)
{
char aff[500];
int x, y;

  while (1)
  {
    if (read(sock, aff, sizeof(aff))>0)
    {
      aff[strchr(aff, 10)-aff-1]=0;
      wprintw(haut, "%s\n", aff+8);
      wrefresh(haut);

      getyx(bas, y, x);
      wmove(bas, y, x);
      wrefresh(bas);
      beep();
    }
    else
      perror("Lecture foirée");
  }
}

int main(int argc, char **argv)
{
struct sockaddr_in adresse;
struct hostent *hp;
char serv[128];
pthread_t thenvoi, threception;
int i;


// traitement des paramètres de la ligne de commande
strcpy(pseudo,"sans nom");
strcpy(couleur,"00000000");
i=1;
while (i<argc)
{
  if (strcmp(argv[i], "-p")==0)
  {
    strcpy(pseudo, argv[i+1]);
    i++;
  }
  else
  {
    if (strcmp(argv[i], "-c")==0)
    {
      strcpy(couleur, argv[i+1]);
      i++;
    }
  }
  i++;
}

signal(SIGCHLD, SIG_IGN);

sock=socket(AF_INET, SOCK_STREAM, 0);

adresse.sin_family=htonl(AF_INET);
adresse.sin_port=htons(2200);

strcpy(serv, "10.10.10.1");
hp = gethostbyname(serv);
bcopy(hp->h_addr, &(adresse.sin_addr), hp->h_length);

initscr();
haut=newwin(LINES-2, COLS, 0, 0);
bas=newwin(2,COLS,LINES-2, 0);
scrollok(haut, TRUE);
idlok(haut, TRUE);

if (connect(sock, &adresse, sizeof(adresse))==0)
{
   pthread_create(&thenvoi, NULL, envoi, 0);
   pthread_create(&threception, NULL, reception, 0);

   while (1)
   {
   }
}
else
  printf("connexion impossible\n");

endwin();
close(sock);

}