/*
 * $Id: asyncore.cxx,v 4.0 2003/04/28 14:44:40 hut66au Exp $
 *
 * Imview, the portable image analysis application
 * http://www.cmis.csiro.au/Hugues.Talbot/imview
 * ----------------------------------------------------------
 *
 *  Imview is an attempt to provide an image display application
 *  suitable for professional image analysis. It was started in
 *  1997 and is mostly the result of the efforts of Hugues Talbot,
 *  Image Analysis Project, CSIRO Mathematical and Information
 *  Sciences, with help from others (see the CREDITS files for
 *  more information)
 *
 *  Imview is Copyrighted (C) 1997-2001 by Hugues Talbot and was
 *  supported in parts by the Australian Commonwealth Science and 
 *  Industry Research Organisation. Please see the COPYRIGHT file 
 *  for full details. Imview also includes the contributions of 
 *  many others. Please see the CREDITS file for full details.
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 * */

// -*- Mode: C++; tab-width: 4 -*-

// first hack at a C++ version of asyncore eventually will support
// files also (read/write rather than recv/send)

// in python, we're really doing a derivation from a builtin socket _class_,
// we might eventually want to reflect here...

// TODO:
// have all socket-related functions assert that the socket has not
// been closed.  [a read event may close it, and a write event may try
// to write or something...]
// Maybe assert valid fileno, too?

#include "imnmspc.hxx" // name space definition etc.
#include "imview.hxx"

#ifdef HAVE_PTHREADS

#include "asyncore.hxx"

socket_map dispatcher::channels;

void dispatcher::add_channel ()
{
  channels[fileno] = this;
}

bool dispatcher::create_socket (int family, int type, int protocol)
{
  int result = socket (family, type, protocol);
  if (result != -1) {
	set_blocking (0);
	fileno = result;
	srv_dbgprintf("dispatcher::create_socket: new socket fd=%d\n", result);
	add_channel();
  }
  return (result != -1);
}

void dispatcher::set_fileno (int fd, bool is_connected)
{
  fileno = fd;
  connected = is_connected;
  add_channel();
}

#ifndef WIN32_NOTCYGWIN
// unix version
#include <fcntl.h>

void dispatcher::set_blocking (bool blocking)
{
  int flag;
  flag = ::fcntl (fileno, F_GETFL, 0);
  if (blocking) {
	flag &= (~O_NDELAY);
  } else {
	flag |= (O_NDELAY);
  }
  ::fcntl (fileno, F_SETFL, flag);
}

#else
void dispatcher::set_blocking (bool blocking)
{
  u_long b = blocking;
  ioctlsocket(fileno, FIONBIO, &b);
}

#endif

int dispatcher::bind (struct sockaddr * addr, size_t length)
{
  return ::bind (fileno, addr, length);
}

int dispatcher::listen (unsigned int n)
{
  // *** assert valid fileno
  accepting = 1;
  return ::listen (fileno, n);
}

int dispatcher::accept (struct sockaddr * addr, size_t * length_ptr)
{
#ifdef ACCEPT_USES_SOCKLEN_T // this is EXTREMELY annoying, but apparently the right thing to do...
	return ::accept (fileno, addr, (socklen_t *)length_ptr);
#else
	return ::accept (fileno, addr, (int*)length_ptr);
#endif
}

int dispatcher::connect (struct sockaddr * addr, size_t length)
{
  int result = ::connect (fileno, addr, length);

  if (result == 0) {
	connected = 1;
	this->handle_connect();
	return 0;
  } else if (is_nonblocking_error (result)) {
	return 0;
  } else {
	// some other error condition
	return -1;
  }
}

int dispatcher::send (const char * buffer, size_t size, int flags)
{
  int result;
#ifndef WIN32_NOTCYGWIN
  if (!flags) {
	// this allows us to use non-sockets with the library
	result = ::write (fileno, buffer, size);
  } else {
	result = ::send (fileno, buffer, size, flags);
  }
#else
  result = ::send (fileno, buffer, size, flags);
#endif
  
  if ((size_t)result == size) {
	// everything was sent
	write_blocked = 0;
	return result;
  } else if (result >= 0) {
	// not all of it was sent, but no error
	write_blocked = 1;
	return result;
  } else if (is_nonblocking_error (result)) {
	write_blocked = 1;
	return 0;
  } else {
	this->handle_error (result);
	this->handle_close ();
	close();
	closed = 1;
	return -1;
  }
	
}

int dispatcher::recv (char * buffer, size_t size, int flags)
{
  int result;

#ifndef WIN32_NOTCYGWIN
  if (!flags) {
	// this allows us to use non-sockets with the library
	result = ::read (fileno, buffer, size);
  } else {
	result = ::recv (fileno, buffer, size, flags);
  }
#else
  result = ::recv (fileno, buffer, size, flags);
#endif

  if (result > 0) {
	return result;
  } else if (result == 0) {
	closed = 1;
	this->handle_close();
	return 0;
  } else if (is_nonblocking_error (result)) {
	return 0;
  } else {
	this->handle_error (result);
	this->handle_close();
	close();
	closed = 1;
	return -1;
  }
}


void dispatcher::close (void)
{
#ifdef WIN32_NOTCYGWIN
	srv_internal_dbgprintf("closing channel #%d\n", fileno);
	::closesocket (fileno);
#else
	int res;
	srv_internal_dbgprintf("closing channel #%d\n", fileno);

	res = ::close (fileno);
	if (res < 0) 
		srv_dbgprintf("Fileno %d not closed: %s\n", fileno, strerror(errno));
	else
		srv_dbgprintf("Fileno %d closed properly\n", fileno);
#endif
	closed = 1;
	return;
}

void dispatcher::handle_read_event (void)
{
  if (accepting) {
	if (!connected) {
	  connected = 1;
	}
	this->handle_accept();
  } else if (!connected) {
	this->handle_connect();
	connected = 1;
	this->handle_read();
  } else {
	this->handle_read();
  }
}

void dispatcher::handle_write_event (void)
{
  if (!connected) {
	this->handle_connect();
	connected = 1;
  }
  write_blocked = 0;
  this->handle_write();
}

// ==================================================
// static functions
// ==================================================

void dispatcher::dump_channels (void)
{
  cerr << "[";
  socket_map::const_iterator i;
  for (i = channels.begin(); i != channels.end(); i++) {
	if (i != channels.begin()) {
	  cerr << ":";
	}
	cerr << ((*i).first);
  }
  cerr << "]" << endl;
}

#include <list>

void dispatcher::delete_closed_channels ()
{
  
  // I'd prefer to use remove_if.

  list<int> hospice;

  for (socket_map::iterator i = channels.begin(); i != channels.end(); i++) {
	  if (((*i).second)->closed) {
		  srv_dbgprintf("Channel being deleted now\n");
		  hospice.push_front ((*i).first);
	}
  }

  for (list<int>::iterator h = hospice.begin(); h != hospice.end(); h++) {
	channels.erase (*h);
  }

}

void dispatcher::poll (struct timeval * timeout)
{
  if (channels.size()) {
	fd_set r,w;
	socket_map::iterator i;

	FD_ZERO (&r);
	FD_ZERO (&w);
	
	int num = 0;

	delete_closed_channels();

	if (!channels.size()) {
		srv_internal_dbgprintf("socket map is empty, should be shutting down\n");
		return;
	}
	
	srv_internal_dbgprintf("\a");
	for (i = channels.begin(); i != channels.end(); i++) {
	  int fd = (*i).first;
	  if (((*i).second)->readable()) {
		FD_SET (fd, &r);
		num++;
		srv_internal_dbgprintf(" r %d", fd);
	  }
	  if (((*i).second)->writable()) {
		FD_SET (fd, &w);
		num++;
		srv_internal_dbgprintf(" w %d", fd);
	  }
	}
	srv_internal_dbgprintf("\b");
	
	if (!num) {
		srv_internal_dbgprintf("selecting() on no channels, should be shutting down %d FD's set\n", num);
		return;
	}
	srv_internal_dbgprintf("calling select() with %d FD's set\n", num);

	// It bothers me that select()'s first argument does not appear to
	// work as advertised... [it hangs like this if called with
	// anything less than FD_SETSIZE, which seems wasteful?]

	// Note: we ignore the 'exception' fd_set - I have never had a
	// need to use it.  The name is somewhat misleading - the only
	// thing I have ever seen it used for is to detect urgent data -
	// which is an unportable feature anyway.

	// int n = ::select (channels.size() + 1, &r, &w, 0, timeout);
	int n = ::select (FD_SETSIZE, &r, &w, 0, timeout);

	srv_internal_dbgprintf("select : %d, channels.size() %d\n", n, channels.size());

	// [we're also trusting it to count down channels in order to quit iterating]

	for (i = channels.begin(); (i != channels.end() && n); ++i) {
	  int fd = (*i).first;
	  if (FD_ISSET (fd, &r)) {
		((*i).second)->handle_read_event();
		n--;
	  }
	  if (FD_ISSET (fd, &w)) {
		((*i).second)->handle_write_event();
		n--;
	  }
	}
  }
}

// do only one loop
int  dispatcher::loop1(struct timeval * timeout)
{
	if (channels.size()) {
		poll(timeout);
		return 1;
	} else
		return 0; // no channel left
}
	
void dispatcher::loop (struct timeval * timeout)
{
  while (channels.size()) {
	poll (timeout);
  }
}

#endif // HAVE_PTHREADS
