#include "inet.h"
#include "util.h"
#include "user.h"

#include <stdio.h>
#include <iostream.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>

#define MAXLINE 512


void str_cli(int socket) 
    {
    char input[MAXLINE];
    int i;
    struct timeval timeout;
    fd_set fdvar, fdread, fdwrite, fdexcept;

    

    FD_ZERO(&fdvar);
    FD_SET(socket, &fdvar);

    for ( ; ; )
        {

        bcopy(&fdvar,&fdread,sizeof(fd_set));
        bcopy(&fdvar,&fdexcept,sizeof(fd_set));
        FD_ZERO(&fdwrite);
        timeout.tv_sec = 5;
        timeout.tv_usec = 0;

        i = select(socket + 1, &fdread, &fdwrite, &fdexcept, &timeout);

        if (i > 0) 
            {
            for (i = 0; i < (socket + 1); i++)
                {
                if(FD_ISSET(i, &fdexcept))
                    return;
                }
            for (i = 0; i < (socket + 1); i++)
                {
                if(FD_ISSET(i, &fdread))
                    {
                    if (i == 0) 
                        { 
                        ParseUserData(UserList, socket);
                    else 
                        ParseServerData(UserList, socket);
                    }
                }
            }
        }
    }

        

main(int argc, char * argv[]) 
    {
    int sockfd, SERV_TCP_PORT = 4000;
    struct sockaddr_in serv_addr;

    SERV_TCP_PORT = atoi(argv[1]);
    pname = argv[0];

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR);
    serv_addr.sin_port = htons(SERV_TCP_PORT);

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        cout << "client: can't open stream socket" << endl;

    if(connect (sockfd, (struct sockaddr *) &serv_addr,
        sizeof(serv_addr)) < 0)
        cout << "client: can't connect to server" << endl;

    str_cli(sockfd);
    close(sockfd);
    exit(0);
    }


