/*
 *
 * UNICON - The Console Chinese & I18N
 * Copyright (c) 1999-2000
 *
 * This file is part of UNICON, a console Chinese & I18N
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See the file COPYING directory of this archive
 * Author: see CREDITS
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/time.h>
#include <assert.h>

#include <iostream.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <TLC_SocketClient.hpp>

struct SocketErrorMsg
{
    int ErrCode;
    char *szMsg;
};

static struct SocketErrorMsg aSocketErrorMsg[] =
{
    {SOCKET_OK          ,   "Socket Ok"},
    {SOCKET_TIME_OUT     ,  "Socket TimeOut"},
};

int TotalErrorMsg = sizeof (aSocketErrorMsg) / sizeof (struct SocketErrorMsg);

char *GetErrorMsg (int ErrCode)
{
    for (int i = 0; i < TotalErrorMsg; i++)
    {
        if (aSocketErrorMsg[i].ErrCode == ErrCode)
            return aSocketErrorMsg[i].szMsg;
    }
    return NULL;
}

TLC_CSocketClient::TLC_CSocketClient (char *szIpAddr, u_short port)
{
    struct sockaddr_in servaddr;
    struct protoent *pe;

    /* create TCP socket */
    if ((pe = getprotobyname("tcp")) == NULL) {
        perror("getprotobyname");
        exit(1);
    }
    if ((fd = socket (AF_INET, SOCK_STREAM, pe->p_proto)) == -1)
    {
        cout << "bad socket ....\n";
        exit (-1);
    }
    memset (&servaddr, 0, sizeof (servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons (port);
    inet_pton (AF_INET, szIpAddr, &servaddr.sin_addr);
    if (connect (fd, (struct sockaddr *) &servaddr, sizeof (servaddr)) == -1)
    {
        printf ("can't connect to %s::%d\n", szIpAddr, port);        
        exit (-1);
    }
    ErrCode = SOCKET_OK;
}

TLC_CSocketClient::~TLC_CSocketClient ()
{
    close (fd);
}

int TLC_CSocketClient::PollRead (char *buf, int len)
{
    char *p = buf;
    int b = len, t;
    fd_set readset;
    struct timeval timeout;
 
    do
    {
        FD_ZERO (&readset);
        FD_SET (fd, &readset);
        timeout.tv_sec = 120;
        timeout.tv_usec = 0;

        if (select (fd+1, &readset, NULL, NULL, &timeout) <= 0)
        {
            ErrCode = SOCKET_TIME_OUT;
            return -1;
        }
        t = read (fd, p, len);
        if (t < 0)
           continue;
        p += t;
        len -= t;
    }
    while (len != 0);
    return b;
}

int TLC_CSocketClient::PollWrite (char *buf, int len)
{
    char *p = buf;
    int b = len, t;
    int do_try = 0;
    do
    {
        t = write (fd, p, len);
        if (t < 0)
        {
           do_try ++;
           continue;
        }
        else
           do_try = 0;
        p += t;
        len -= t;
    }
    while (len != 0 && do_try < 5);
    if (do_try >= 5)
        return -1;
    return b;
}

int TLC_CSocketClient::Read (char *buf, int max)
{
    short len;
    if (PollRead ((char *) &len, sizeof (short)) == -1)
        return -1;
    assert (len < max);
#ifdef __IMM_DEBUG__
    printf ("receiving:\n");
#endif
    if (PollRead (buf, len) == -1)
        return -1;
#ifdef __IMM_DEBUG__
    printf ("(len = %d)", len);
    for (int i = 0; i < len; i++)
        printf ("(0x%x,%c)", buf[i], buf[i]);
    printf ("\n");
#endif
    return len;
}

int TLC_CSocketClient::Write (char *buf, int len)
{
    short len0 = len;
#ifdef __IMM_DEBUG__
    printf ("sending: len = %d\n", len);
#endif
    if (PollWrite ((char *) &len0, sizeof (short)) == -1)
        return -1;
    if (PollWrite ((char *) buf, len) == -1)
        return -1;
#ifdef __IMM_DEBUG__
    for (int i = 0; i < len; i++)
        printf ("(0x%x,%c)", buf[i], buf[i]);
    printf ("\n");
#endif
    return len;
}

