/*******************************************************************************
 * 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.jdshot.search;

import edu.duke.donaldLab.jdshot.context.DistanceRestraintsContext;
import edu.duke.donaldLab.jdshot.context.SymmetryContext;
import edu.duke.donaldLab.jdshot.grid.GridCell;
import edu.duke.donaldLab.jdshot.grid.SearchSpace;
import edu.duke.donaldLab.jdshot.search.messages.CellsRequest;
import edu.duke.donaldLab.jdshot.search.messages.CellsResponse;
import edu.duke.donaldLab.jdshot.search.messages.CellsResult;
import edu.duke.donaldLab.share.mpi.Client;
import edu.duke.donaldLab.share.mpi.MPIEndpoint;
import edu.duke.donaldLab.share.nmr.Assignment;
import edu.duke.donaldLab.share.nmr.DistanceRestraint;
import edu.duke.donaldLab.share.protein.AtomAddressInternal;

public class SearchClient extends Client
{
	/**************************
	 *   Definitions
	 **************************/
	
	private final int DefaultBatchSize = 200;
	
	
	/**************************
	 *   Data Members
	 **************************/

	private SymmetryContext m_symmetryContext;
	private DistanceRestraintsContext m_distanceRestraintsContext;
	private CellChecker m_checker;
	private int m_batchSize;
	
	
	/**************************
	 *   Constructors
	 **************************/
	
	public SearchClient( SymmetryContext symmetryContext, DistanceRestraintsContext distanceRestraintsContext )
	{
		m_symmetryContext = symmetryContext;
		m_distanceRestraintsContext = distanceRestraintsContext;
		
		// init defaults
		m_checker = m_symmetryContext.getSymmetry().newCellChecker( m_symmetryContext );
		m_batchSize = DefaultBatchSize;
	}
	
	
	/**************************
	 *   Accessors
	 **************************/
	
	public void setBatchSize( int val )
	{
		m_batchSize = val;
	}
	
	
	/**************************
	 *   Methods
	 **************************/

	@Override
	protected void run( ) throws Exception
	{
		int numProcessed = 0;
		
		SearchSpace searchSpace = m_symmetryContext.newSearchSpace( m_distanceRestraintsContext.getMaxRestraint().getMaxDistance() );
		CellSplitter splitter = m_symmetryContext.getSymmetry().newCellSplitter( searchSpace );
		
		// preallocate memory for messages and buffers
		CellsResult result = new CellsResult( m_batchSize, m_symmetryContext.getSymmetry(), m_distanceRestraintsContext.getInternalRestraints() );
		
		MPIEndpoint.sendMessageToServer( new CellsRequest( m_batchSize ) );
		while( true )
		{
			// get cells from the server
			CellsResponse response = (CellsResponse)MPIEndpoint.waitForMessage();
			
			// if no cells, exit
			if( response.cells.size() == 0 )
			{
				break;
			}
			// if we're on the last batch, resize the buffers
			else if( response.cells.size() < m_batchSize )
			{
				result.resizeCells( response.cells.size() * 2, m_symmetryContext.getSymmetry() );
			}
			
			// do the work and send the result back to the server
			result.consistency.reset();
			result.startIndex = response.startIndex * 2;
			for( int i=0; i<response.cells.size(); i++ )
			{
				GridCell cell = response.cells.get( i );
				
				// split the cell and process both children
				GridCell leftCell = result.cells.get( i * 2 );
				GridCell rightCell = result.cells.get( i * 2 + 1 );
				splitter.split( leftCell, rightCell, cell );
				processCell( leftCell, i * 2, result.consistency );
				processCell( rightCell, i * 2 + 1, result.consistency );
			}
			MPIEndpoint.sendMessageToServer( result );
			
			numProcessed += result.cells.size();
		}
		
		MPIEndpoint.log( "Client finished! processed " + numProcessed + " cells" );
	}
	
	
	/**************************
	 *   Methods
	 **************************/
	
	private void processCell( GridCell cell, int cellIndex, Consistency consistency )
	{
		// for each restraint...
		int numRestraints = m_distanceRestraintsContext.getInternalRestraints().size();
		for( int i=0; i<numRestraints; i++ )
		{
			DistanceRestraint<AtomAddressInternal> restraint = m_distanceRestraintsContext.getInternalRestraints().get( i );
			
			int j = 0;
			int numInconsistentAssignments = 0;
			for( Assignment<AtomAddressInternal> assignment : restraint )
			{
				if( m_checker.isConsistent( cell, restraint.getMaxDistance(), assignment ) )
				{
					consistency.markRestraintConsistent( i, j );
				}
				else
				{
					numInconsistentAssignments++;
				}
				
				j++;
			}
			
			if( numInconsistentAssignments == j )
			{
				consistency.markCellInconsistent( cellIndex );
			}
		}
	}
}
