/**
 * MapGenerator Sample Extensions
 */
package mycompany.map.modificator;

import java.util.logging.Level;
import java.util.logging.Logger;

import idea.map.generator.MapGenerator;
import idea.map.matrix.AbstractMatrix;

/**
 * Worker thread for UserModificator
 * 
 * @author Lumir Vanek, vanek@idea-envi.cz
 *
 */
public class UserModificatorThread implements Runnable 
{
	/**
	 * Name of the thread
	 */
	private final String name;
	
	/**
	 * Matrix to modify values
	 */
	private final AbstractMatrix matrix;
	
	/**
	 * The value, used in modification
	 */
	private final float modificator;
	
	/**
	 * First matrix row, modified by this thread 
	 */
	private final int startRow;
	
	/**
	 * Last matrix row, modified by this thread 
	 */
	private final int endRow;

	/**
	 * Constructor
	 * 
	 * @param name Thread name
	 * @param matrix Matrix for filter values
	 * @param The value, used in modification
	 * @param startRow First matrix row, computed by this thread 
	 * @param endRow Last matrix row, computed by this thread 
	 */
	public UserModificatorThread(String name, 
			AbstractMatrix matrix,
			float modificator,
			int startRow,
			int endRow)
	{
		this.name = name;
		this.matrix = matrix;
		this.modificator = modificator;
		this.startRow = startRow;
		this.endRow = endRow;
	}

	/**
	 * Do your work
	 */
	public void run()
	{
		try
		{
			long startTime = System.currentTimeMillis();
				
			for(int row = startRow; row <= endRow; row++)
			{
				for(int column = 0; column < matrix.getColumns(); column++)
				{
					modifyCell(row, column);
				}
			}
			
			long endTime = System.currentTimeMillis();
			float elapsedTime = (endTime - startTime) / 1000.0f;
			
			Logger.getLogger(MapGenerator.loggerName).finer(name + 
				" of matrix " + matrix.getId() + " finished in " + elapsedTime + " sec.");
		}
		catch(Throwable t)
		{
			Logger.getLogger(MapGenerator.loggerName).log(Level.SEVERE, 
					name + " of matrix " + matrix.getId() + " died", 
					t);
		}
	}
	
	/**
	 * Modify one cell value
	 * 
	 * @param row Matrix row
	 * @param column Matrix column
	 */
	private void modifyCell(int row, int column)
	{
		if(matrix.getValue(row, column) == null) return;
		
		Float value = (matrix.getValue(row, column));
		//***************************************************
		//***************************************************
		
		value = value * 1 / modificator; // Only sample, use own formula
		
		//***************************************************
		//***************************************************
		matrix.setValue(row, column, value);
	}
}