package edu.unl.consystlab.sudokuSolver;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class assignSingletons {

	//variableReductions should equal variablesAssigned, but we keep them separate
	// because they have different meanings and are gathered in different ways.
	private constraintProblem parentProblem;
	private List variableReductions;
	private List variablesAssigned;
	
	public assignSingletons(constraintProblem newProblem) {
		parentProblem = newProblem;
		variableReductions = new LinkedList();
		variablesAssigned = new LinkedList();
	}

	public void runAlgorithm()
	{
		variablesAssigned = new LinkedList();
		variableReductions = new LinkedList();
		parentProblem.registerDomainReductionListener(variableReductions);
		//get all variables
		List allVariables = new LinkedList(parentProblem.getAllVariables());
		//assign all the ones that have one value
		Iterator i = allVariables.iterator();
		while(i.hasNext())
		{
			problemVariable currentVar = (problemVariable)i.next();
			if(!currentVar.isAssigned())
			{
				if(1 == currentVar.getCurrentDomainSize())
				{
					String newValue = currentVar.getCurrentDomainFirstValue();
					variableIndexAndValueGrouping tempGrouping = 
						new variableIndexAndValueGrouping(currentVar.getIndex(), newValue);
					variablesAssigned.add(tempGrouping);
					currentVar.setAssigned(newValue);
				}
			}
		}

		parentProblem.unregisterDomainReductionList(variableReductions);
		return;
	}

	public void setVariableReductions(List variableReductions) {
		this.variableReductions = variableReductions;
	}

	public List getVariableReductions() {
		return variableReductions;
	}

	public void setVariablesAssigned(List variablesAssigned) {
		this.variablesAssigned = variablesAssigned;
	}

	public List getVariablesAssigned() {
		return variablesAssigned;
	}
}
