/*******************************************************************************
 * 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
 * 
 * Contact Info:
 * 	Bruce Donald
 * 	Duke University
 * 	Department of Computer Science
 * 	Levine Science Research Center (LSRC)
 * 	Durham
 * 	NC 27708-0129 
 * 	USA
 * 	brd@cs.duke.edu
 * 
 * Copyright (C) 2011 Jeffrey W. Martin and Bruce R. Donald
 * 
 * <signature of Bruce Donald>, April 2011
 * Bruce Donald, Professor of Computer Science
 ******************************************************************************/


package edu.duke.donaldLab.share.mpi;

import java.lang.reflect.Method;
import java.util.ArrayList;

import edu.duke.donaldLab.share.mpi.messages.ClientException;
import edu.duke.donaldLab.share.perf.MessageListener;

public abstract class Server implements MessageListener
{
	/**************************
	 *   Data Members
	 **************************/
	
	private ArrayList<ClientState> m_states;
	
	
	/**************************
	 *   Constructors
	 **************************/
	
	public Server( )
	{
		m_states = null;
	}
	
	
	/**************************
	 *   Events
	 **************************/
	
	public void message( String msg )
	{
		MPIEndpoint.log( msg );
	}
	
	public void handleMessage( ClientException ex )
	{
		setClientState( ex.getSourceRank(), ClientState.Crashed );
		
		MPIEndpoint.log( String.format( "Exception from client %d!", ex.getSourceRank() ) );
		MPIEndpoint.reportExceptionAs( ex.exception, ex.getSourceRank() );
	}
	
	
	/**************************
	 *   Methods
	 **************************/
	
	public void run( )
	throws InterruptedException
	{
		MPIEndpoint.log( String.format( "Server started, %d clients detected", MPIEndpoint.getNumClients() ) );
		if( MPIEndpoint.getNumClients() <= 0 )
		{
			MPIEndpoint.log( "No clients! Aborting!" );
			return;
		}
		
		// assume all clients are active until proven otherwise
		m_states = new ArrayList<ClientState>( MPIEndpoint.getNumClients() );
		for( int i=0; i<MPIEndpoint.getNumClients(); i++ )
		{
			m_states.add( ClientState.Active );
		}
		
		try
		{
			init();
		}
		catch( Exception ex )
		{
			MPIEndpoint.reportException( ex );
			return;
		}
		
		// wait for messages while we still have clients
		while( getNumActiveClients() > 0 )
		{
			try
			{
				// get the next message
				Message message = MPIEndpoint.waitForMessage();
				if( message == null )
				{
					continue;
				}
				
				Class<? extends Message> c = message.getClass();
				
				// UNDONE: cache method lookups
				// UNDONE: change to use interfaces?
				
				// call its handler
				Method method = getClass().getMethod( "handleMessage", c );
				if( method == null )
				{
					MPIEndpoint.log( "No handler found for " + c.getName() );
					continue;
				}
				method.invoke( this, message );
			}
			catch( InterruptedException ex )
			{
				throw ex;
			}
			catch( Exception ex )
			{
				MPIEndpoint.reportException( ex );
			}
		}
		
		MPIEndpoint.log( "All clients finished. Server shutting down..." );
		
		try
		{
			shutdown();
		}
		catch( Exception ex )
		{
			MPIEndpoint.reportException( ex );
		}
	}
	
	
	/**************************
	 *   Functions
	 **************************/
	
	protected abstract void init( )
	throws Exception;
	
	protected abstract void shutdown( )
	throws Exception;
	
	protected int getClientId( int rank )
	{
		return rank - 1;
	}
	
	protected ClientState getClientState( int rank )
	{
		return m_states.get( getClientId( rank ) );
	}
	
	protected void setClientState( int rank, ClientState state )
	{
		m_states.set( getClientId( rank ), state );
	}
	
	protected int getNumActiveClients( )
	{
		// UNDONE: maybe there's a way to speed this up accurately
		
		int count = 0;
		for( ClientState state : m_states )
		{
			if( state == ClientState.Active )
			{
				count++;
			}
		}
		return count;
	}
}
