package de.ugoe.cs.swe.bnftools.validation;

import java.util.Map;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.validation.NamesAreUniqueValidationHelper;
import org.eclipse.xtext.validation.ValidationMessageAcceptor;

import com.google.common.collect.Maps;

import de.ugoe.cs.swe.bnftools.ebnf.ExtRule;
import de.ugoe.cs.swe.bnftools.ebnf.MergeRule;

public class EbnfNamesAreUniqueValidationHelper extends
		NamesAreUniqueValidationHelper {
	
	protected void checkDescriptionForDuplicatedName(
			IEObjectDescription description,
			Map<EClass, Map<String, IEObjectDescription>> clusterTypeToName,
			ValidationMessageAcceptor acceptor) {
		
		EObject object = description.getEObjectOrProxy();
		EClass eClass = object.eClass();
		String qualifiedName = description.getName();
		EClass clusterType = getAssociatedClusterType(eClass);
		
		if (object instanceof ExtRule)
			return;
		if(object instanceof MergeRule)
			return;
		Map<String, IEObjectDescription> nameToDescription = clusterTypeToName.get(clusterType);
		
		if (nameToDescription == null) {
			nameToDescription = Maps.newHashMap();
			nameToDescription.put(qualifiedName, description);
		
			clusterTypeToName.put(clusterType, nameToDescription);
		} else {
			if (nameToDescription.containsKey(qualifiedName)) {
				IEObjectDescription prevDescription = nameToDescription.get(qualifiedName);
				if (prevDescription != null) {
					createDuplicateNameError(prevDescription, clusterType, acceptor);
					nameToDescription.put(qualifiedName, null);
				}
				createDuplicateNameError(description, clusterType, acceptor);
			} else {
				nameToDescription.put(qualifiedName, description);
			}
		}
	}

}
