// ---------------------------------------------------------------------------
// - TcpSocket.cpp                                                           -
// - afnix:net module - tcp socket class implementation                      -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - 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.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Ascii.hpp"
#include "Vector.hpp"
#include "Integer.hpp"
#include "Boolean.hpp"
#include "TcpSocket.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "csio.hpp"
#include "cnet.hpp"
#include "cerr.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default tcp socket

  TcpSocket::TcpSocket (void) {
    d_sid = c_ipsocktcp ();
    if (d_sid < 0) throw Exception ("tcp-error", c_errmsg (d_sid));
  }

  // create a socket by id 

  TcpSocket::TcpSocket (const int sid) {
    d_sid = sid;
    if (d_sid < 0) throw Exception ("tcp-error", "invalid tcp socket");
  }

  // create a tcp socket by flag

  TcpSocket::TcpSocket (const bool cflg) {
    if (cflg == true) {
      d_sid = c_ipsocktcp ();
      if (d_sid < 0) throw Exception ("tcp-error", c_errmsg (d_sid));
    }
  }

  // return the class name

  String TcpSocket::repr (void) const {
    return "TcpSocket";
  }

  // return true if the eos flag is set

  bool TcpSocket::iseos (void) const {
    wrlock ();
    try {
      if (d_sbuf.length () != 0) {
	unlock ();
	return false;
      }
      // check if we can read one character
      bool status = c_rdwait (d_sid, 0);
      if (status == false) {
	unlock ();
	return false;
      }
      // read in the character - might be the eos
      char c = nilc;
      if (c_read (d_sid, &c, 1) <= 0) {
	unlock ();
	return true;
      }
      d_sbuf.pushback (c);
      unlock ();
      return false;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // check if we can read one character

  bool TcpSocket::valid (void) const {
    wrlock ();
    try {
      if (d_sbuf.length () != 0) {
	unlock ();
	return true;
      }
      // check if we can read one character
      bool status = c_rdwait (d_sid, d_tout);
      if (status == false) {
	unlock ();
	return false;
      }
      // read in the character - might be the eos
      char c = nilc;
      if (c_read (d_sid, &c, 1) <= 0) {
	unlock ();
	return false;
      }
      d_sbuf.pushback (c);
      unlock ();
      return true;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // read one character from the socket

  char TcpSocket::read (void) {
    wrlock ();
    try {
      // check if we can read a character
      if (valid () == false) {
	unlock ();
	return eosc;
      }
      // check the pushback buffer first
      if (d_sbuf.empty () == false) {
	char result = d_sbuf.read ();
	unlock ();
	return result;
      }
      // read the next character in case valid
      // does not push a character (safety code only)
      char c = nilc;
      long count = 0;
      if ((count = c_read (d_sid, &c, 1)) < 0) {
	throw Exception ("read-error", c_errmsg (count));
      }
      // check for eos
      if (count == 0) c = eosc;
      unlock ();
      return c;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // copy the tcp socket into a buffer

  long TcpSocket::copy (char* rbuf, const long size) {
    // check argument first
    if ((rbuf == nilp) || (size <= 0)) return 0;
    // lock and fill
    wrlock ();
    try {
      // initialize result
      long result = 0;
      // check the pushback buffer first
      for (long i = 0; i < size; i++) {
	if (d_sbuf.empty () == true) break;
	rbuf[i] = d_sbuf.read ();
	result++;
      }
      if (result == size) {
	unlock ();
	return result;
      }
      // check if we can read one character
      bool status = c_rdwait (d_sid, d_tout);
      if (status == false) {
	unlock ();
	return result;
      }
      // read by block
      long count = 0;
      if ((count = c_read (d_sid, &rbuf[result], size-result)) < 0) {
	throw Exception ("read-error", c_errmsg (count));
      }
      result+= count;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // write one character to the socket
  
  long TcpSocket::write (const char value) {
    wrlock ();
    try {
      long result = c_write (d_sid, &value, 1);
      if (result < 0) throw Exception ("write-error", c_errmsg (result));
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // write a data buffer to the socket

  long TcpSocket::write (const char* data) {
    // lock and write
    wrlock ();
    try {
      // check for size first
      long size = Ascii::strlen (data);
      if (size == 0) {
	unlock ();
	return 0;
      }
      long result = c_write (d_sid, data, size);
      if (result < 0) throw Exception ("write-error", c_errmsg (result));
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // write a character array to the socket

  long TcpSocket::write (const char* rbuf, const long size) {
    // check argument first
    if ((rbuf == nilp) || (size <= 0)) return 0;
    // lock and write
    wrlock ();
    try {
      long result = 0;
      while (result != size) {
	long count = c_write (d_sid, &rbuf[result], size-result);
	if (count < 0) throw Exception ("write-error", c_errmsg (result));
	if (count == 0) break;
	result += count;
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // create a tcp socket by address family

  void TcpSocket::create (const Address& addr) {
    wrlock ();
    try {
      if (d_sid != -1) {
	throw Exception ("tcp-error", "tcp socket already created");
      }
      d_sid = c_ipsocktcp (addr.p_addr);
      if (d_sid < 0) {
	throw Exception ("tcp-error", c_errmsg (d_sid));
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  bool TcpSocket::listen (const long backlog) const {
    rdlock ();
    try {
      bool result = c_iplisten (d_sid, backlog);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // accept a connection from this tcp socket

  TcpSocket* TcpSocket::accept (void) const {
    rdlock ();
    try {
      int sid = c_ipaccept (d_sid);
      if (sid < 0) throw Exception ("accept-error", c_errmsg (sid));
      TcpSocket* result = new TcpSocket (sid);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 2;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_ACCEPT = zone.intern ("accept");
  static const long QUARK_LISTEN = zone.intern ("listen");

  // create a new object in a generic way

  Object* TcpSocket::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    // check for 0 argument
    if (argc == 0) return new TcpSocket;
    // check for 1 argument
    if (argc == 1) {
      bool cflg = argv->getbool (0);
      return new TcpSocket (cflg);
    }
    throw Exception ("argument-error", 
		     "too many arguments with tcp socket constructor");
  }

  // apply this object with a set of arguments and a quark

  Object* TcpSocket::apply (Runnable* robj, Nameset* nset, const long quark,
			    Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();

    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_ACCEPT) return accept ();
      if (quark == QUARK_LISTEN) return new Boolean (listen (5));
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_LISTEN) {
	long backlog = argv->getlong (0);
	return new Boolean (listen (backlog));
      }
    }
    // call the socket method
    return Socket::apply (robj, nset, quark, argv);
  }
}
