/*******************************************************************************
 * 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 java.util.ArrayList;
import java.util.List;

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.share.nmr.DistanceRestraint;
import edu.duke.donaldLab.share.nmr.Assignment;
import edu.duke.donaldLab.share.protein.AtomAddressInternal;

public class SearchProcessor implements Runnable
{
	/**************************
	 *   Definitions
	 **************************/
	
	private final int DefaultBatchSize = 100;
	
	
	/**************************
	 *   Data Members
	 **************************/
	
	private SearchProcessorSynchronizer m_synch;
	private CellChecker m_checker;
	private CellSplitter m_splitter;
	private SymmetryContext m_symmetryContext;
	private DistanceRestraintsContext m_distanceRestraintsContext;
	private List<GridCell> m_oldCells;
	private ArrayList<GridCell> m_cellsToSave;
	private int[] m_cellsToSaveIndices; // using basic array for mutability
	private Consistency m_consistency;
	private int m_batchSize;
	
	
	/**************************
	 *   Constructors
	 **************************/
	
	public SearchProcessor( SearchProcessorSynchronizer synch, SymmetryContext symmetryContext, DistanceRestraintsContext distanceRestraintsContext, List<GridCell> oldCells )
	{
		// save parameters
		m_synch = synch;
		m_symmetryContext = symmetryContext;
		m_distanceRestraintsContext = distanceRestraintsContext;
		m_oldCells = oldCells;
		
		// init defaults
		SearchSpace searchSpace = m_symmetryContext.newSearchSpace( m_distanceRestraintsContext.getMaxRestraint().getMaxDistance() );
		m_splitter = m_symmetryContext.getSymmetry().newCellSplitter( searchSpace );
		m_checker = m_symmetryContext.getSymmetry().newCellChecker( m_symmetryContext );
		m_consistency = new Consistency( 1, m_distanceRestraintsContext.getInternalRestraints() );
		m_batchSize = DefaultBatchSize;
		resizeBuffers( m_batchSize * 2 );
	}
	
	
	/**************************
	 *   Accessors
	 **************************/
	
	public void setBatchSize( int val )
	{
		m_batchSize = val;
		resizeBuffers( m_batchSize * 2 );
	}
	
	
	/**************************
	 *   Methods
	 **************************/
	
	public void run( )
	{
		// TEMP
		System.out.println( "Thread starting..." );
		
		GridCell left = m_symmetryContext.getSymmetry().newGridCell();
		GridCell right = m_symmetryContext.getSymmetry().newGridCell();
		int numProcessed = 0;
		
		while( true )
		{
			// get the next batch of cells if there is one
			int[] indices = m_synch.getNextIndices( m_batchSize );
			if( indices == null )
			{
				break;
			}
			int numNewCells = indices.length * 2;
			
			// resize buffers if needed
			if( indices.length != m_batchSize )
			{
				resizeBuffers( numNewCells );
			}
			
			int bufferIndex = 0;
			for( int i=0; i<indices.length; i++ )
			{
				GridCell cell = m_oldCells.get( indices[i] );
				
				// split the cell and process both children
				m_splitter.split( left, right, cell );
				processCell( left, indices[i] * 2, bufferIndex++ );
				processCell( right, indices[i] * 2 + 1, bufferIndex++ );
			}
			
			// send updates
			m_synch.saveCells( m_cellsToSave, m_cellsToSaveIndices );
			m_synch.mergeConsistency( m_consistency, indices[0] * 2 );
			m_consistency.reset();
			
			numProcessed += numNewCells;
		}
		
		// TEMP
		System.out.println( "Thread finished! processed " + numProcessed + " cells" );
	}
	
	
	/**************************
	 *   Functions
	 **************************/
	
	private void resizeBuffers( int numCells )
	{
		m_consistency.resizeCells( numCells );
		m_cellsToSave = new ArrayList<GridCell>( numCells );
		for( int i=0; i<numCells; i++ )
		{
			m_cellsToSave.add( m_symmetryContext.getSymmetry().newGridCell() );
		}
		m_cellsToSaveIndices = new int[numCells];
	}
	
	private void processCell( GridCell cell, int cellIndex, int bufferIndex )
	{
		// 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 ) )
				{
					m_consistency.markRestraintConsistent( i, j );
				}
				else
				{
					numInconsistentAssignments++;
				}
				
				j++;
			}
			
			if( numInconsistentAssignments == j )
			{
				m_consistency.markCellInconsistent( bufferIndex );
			}
		}
		
		// save the cell
		m_cellsToSave.get( bufferIndex ).set( cell );
		m_cellsToSaveIndices[bufferIndex] = cellIndex;
	}
}
