/*
 *
 *
 *    multiplex.cc
 *
 *    C++ source code for class my::multiplex member functions and/or static
 *    member data.
 *
 *    =========================================================================
 *
 *    Copyright (C) 1999-2003 by Matt Roberts, KK5JY.
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *    =========================================================================
 *
 *
 */


#include <algorithm>
#include <my++/watchable.h>
#include <my++/multiplex.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <unistd.h>
#include <errno.h>


/*
 *
 *   my::multiplex::set(...)
 *
 */

void my::multiplex::add (my::watchable *d) {
	dev_list::iterator i = find (devices.begin(), devices.end(), d);

	if (i == devices.end())
		devices.push_back(dev_node(d));
}


/*
 *
 *   my::multiplex::clear (...)
 *
 */

void my::multiplex::remove (my::watchable *d) {
	dev_list::iterator i = find (devices.begin(), devices.end(), d);

	if (i != devices.end())
		devices.erase(i);
}


/*
 *
 *   my::multiplex::watch (...)
 *
 *   watch (...) will assemble the fd_set structures, call 'select' and then if 'select'
 *   returns >0, will cycle through the devices so they can update their states.  watchAll()
 *   will return an int indicating how many devices have events.
 *
 */

int my::multiplex::watch(timeval *timeout) {
	// local variables
	fd_set read_set, write_set, except_set;
	dev_list::iterator i;
	int rtn, count;
	int n, fd;

	bool do_continue;

	m_signalled = false;

	do {
		// start with clean file descriptor sets
		FD_ZERO(&read_set);
		FD_ZERO(&write_set);
		FD_ZERO(&except_set);

		// and with no return events
		rtn = 0;

		// build the file descriptor sets
		n = 0;
		for (i = devices.begin(); i != devices.end(); ++i) {
			// if we watch read for this device, set it up
			if (i->dev->should_watch_read()) {
				if ((fd = i->dev->read_desc()) >= 0) {
					i->watch_read = true;
					FD_SET(fd, &read_set);
					if (fd > n) n = fd;
				}
			}

			// if we watch write for this device, set it up
			if (i->dev->should_watch_write()) {
				if ((fd = i->dev->write_desc()) >= 0) {
					i->watch_write = true;
					FD_SET(fd, &write_set);
					if (fd > n) n = fd;
				}
			}

			// if we watch for exception on this device, set it up
			if (i->dev->should_watch_except()) {
				if ((fd = i->dev->except_desc()) >= 0) {
					i->watch_except = true;
					FD_SET(fd, &except_set);
					if (fd > n) n = fd;
				}
			}
		}

		// sleep until something happens
		count = ::select (n + 1, &read_set, &write_set, &except_set, timeout);

		// deal with the return value...
		if (count > 0) {          // devices were waiting
			bool rtn_event = false;

			for (i = devices.begin(); i != devices.end(); ++i) {
				rtn_event = false;

				if ((i->watch_read) && ((fd = i->dev->read_desc()) >= 0))
					if (FD_ISSET(fd, &read_set))
						rtn_event = rtn_event || i->dev->read_action();

				if ((i->watch_write) && ((fd = i->dev->write_desc()) >= 0))
					if (FD_ISSET(fd, &write_set))
						rtn_event = rtn_event || i->dev->write_action();

				if ((i->watch_except) && ((fd = i->dev->except_desc()) >= 0))
					if (FD_ISSET(fd, &except_set))
						rtn_event = rtn_event || i->dev->except_action();

				// if a valid event occurred, include it in the count
				if (rtn_event) ++rtn;
			}
		} else if (count == 0) {  // (count == 0): select() timed out
			rtn = 0;
		} else {                  // (count <  0): select() error occurred
			if (count < 0) {
				switch (errno) {
					case EINTR:
						m_signalled = true;
						return 0;
					case EBADF:
					case EINVAL:
					case ENOMEM:
					default:
						throw my::multiplex::exception(this, errno);
				}
			}

			// if we got errno==EINTR, then just act like we timed out with nothing
			// happening
			timeout->tv_sec = 0;
			timeout->tv_usec = 0;
			rtn = 0;
		}

		if (rtn == 0) {
			if (timeout != 0)
				do_continue = ((timeout->tv_sec > 0) && (timeout->tv_usec > 0));
			else
				do_continue = true;
		} else {
			do_continue = false;
		}
	} while (do_continue);

	// finally, return the number of valid events
	return rtn;
}
