/*
 * CSP Project
 * Authors:
 * 		Jay Bernardo
 * 		Matt Rancourt
 * 
 * File: SemiSuperResolution.java
 * 
 * Contains the SemiSuperResolution class. This transition takes all of the decided
 * variables in M, negates them, and generates the appropriately sized OR relation
 * among those variables
 *  
 */
import java.util.*;

class SemiSuperResolution extends Transition{
	
	
	Relation newRelation;
	
	public SemiSuperResolution(TransitionAssignment M, CSP F){
		super(M, F);
		newRelation = null;
	}
	
	/**
	 * This method determines the OR relation to be added to F among the negated decision
	 * variables in M.
	 * 
	 * NOTE: This stores the relation in the member data "newRelation". It is the
	 *       repsonibility of the caller of SSR.doTransition() to use this data
	 *       in conjunction with the Restart transition
	 * 
	 * @return unused
	 * 
	 */
	public int doTransition()
	throws
		InvalidVariableValueException,
		RelationNumberOutOfBoundsException,
		RankOutOfBoundsException,
		InvalidVariableNamesLengthException,
		VariablePositionOutOfBoundsException{
		
		// For all decided variables in M, add them as an OR relation
		ArrayList<Variable> list = M.getNegatedDecidedVariables();
		int size = list.size();
		String names[] = new String[size];
		
		Iterator<Variable>it = list.iterator();
		int i = 0;
		while(it.hasNext()){
			Variable v = it.next();
			String varName = v.getName();
			if(v.getPositive() == false){
				varName = String.format("!%s", varName);
			}
			
			names[i] = new String(varName);
			i ++;
		}
		
		// Create the appropriate relation given
		// the number of variables we are ORing together
		if(size == 1){
			newRelation = new Relation(2, 1, names);
			newRelation = newRelation.preprocess();
		}
		else if(size == 2){
			newRelation = new Relation(14, 2, names);
			newRelation = newRelation.preprocess();
		}
		else if(size == 3){
			newRelation = new Relation(254, 3, names);
			newRelation = newRelation.preprocess();
		}
		else{
			// We need to turn all the variables to positives explicitly,
			// because SSRelation does not have a preprocess function
			// TODO: Make this a function because it's called in SSRelation.reduce
			// Do that!
			int negatives = 0;
			boolean slot1 = false;
			boolean slot2 = false;
			if(names[0].charAt(0) == '!'){
				// Remove the negativity
				names[0] = String.format("%s", names[0].substring(1));
				negatives ++;
				slot1 = true;
				
			}
			
			if(names[1].charAt(0) == '!'){
				// Remove the negativity
				names[1] = String.format("%s", names[1].substring(1));
				negatives ++;
				slot2 = true;
			}
		
			int relationNumber = 254;
			if(negatives == 1){
				if(slot1)
					relationNumber = 239;
				else if(slot2)
					relationNumber = 251;
			}
			else if(negatives == 2)
				relationNumber = 191;
				
			newRelation = new SSRelation(relationNumber, 3, SSRelation.mungeVariableNamesIn(names), 
												 SSRelation.mungedVariablesList(names));
		}
		
		return -1;
	}
}