package de.dhbwstuttgart.bytecode.utilities;

import java.util.ArrayList;
import java.util.List;

import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.ConstraintsWithSameLeftSide;

public class ConstraintsFinder {
	private List<TPHConstraint> allConstaints;

	public ConstraintsFinder(List<TPHConstraint> allConstaints) {
		this.allConstaints = allConstaints;
	}

	public List<ConstraintsWithSameLeftSide> findConstraints() {
		List<ConstraintsWithSameLeftSide> result = new ArrayList<>();
		
		List<TPHConstraint> visitedCons = new ArrayList<>();
		for(TPHConstraint c : allConstaints) {
			if(c.getRel() == Relation.EXTENDS) {
				// get constraints with the same left side
				List<TPHConstraint> cons = getConstraints(c,visitedCons);
				if(cons.size()>1) {
					ConstraintsWithSameLeftSide consWithSameLeftSide = new ConstraintsWithSameLeftSide(cons);
					result.add(consWithSameLeftSide);
				}
			}
		}
		
		return result;
	}
	
	private List<TPHConstraint> getConstraints(TPHConstraint c, List<TPHConstraint> visitedCons) {
		List<TPHConstraint> res = new ArrayList<>();
		for(TPHConstraint cons : allConstaints) {
			if(!isVisited(cons,visitedCons) && cons.getLeft().equals(c.getLeft())) {
				res.add(cons);
				visitedCons.add(cons);
			}
		}
		return res;
	}

	private boolean isVisited(TPHConstraint cons, List<TPHConstraint> visitedCons) {
		for(TPHConstraint c : visitedCons) {
			if(c.getLeft().equals(cons.getLeft()) && c.getRight().equals(cons.getRight()))
				return true;
		}
		return false;
	}
}
