package antipatternsrecovery.metrics;

import java.util.Vector;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

/*
 * A class's number of children (NOC) metric simply measures the number of immediate descendants of the class.
 */
public class NOC {
	IJavaProject javaProject;

	public int computeNOC(ICompilationUnit pClass) {
		this.javaProject=pClass.getJavaProject();
		int noc=0;

		if(pClass.exists()) {
			Vector<String> superclasses=this.getAllSuperclasses();
			IType type=pClass.getType(pClass.getElementName().substring(0, pClass.getElementName().length()-5));

			for(String superclass: superclasses) {
				if(superclass.equals(type.getElementName()))
					noc++;
			}
		}
		return noc;
	}

	private Vector<String> getAllSuperclasses() {
		Vector<String> superclasses=new Vector<String>();

		try {
			for(IPackageFragment pack: this.javaProject.getPackageFragments()){
				for(ICompilationUnit cu: pack.getCompilationUnits()) {
					for(IType type: cu.getTypes()) {
						if(type.getSuperclassName()!=null)
							superclasses.add(type.getSuperclassName());
					}
				}
			}
		} catch (JavaModelException e) {
			e.printStackTrace();
		}

		return superclasses;
	}
}
