package antipatternsrecovery.metrics;

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;

/*
 * The depth of inheritance tree (DIT) metric provides for each class a measure 
 * of the inheritance levels from the object hierarchy top. In Java where all classes 
 * inherit Object the minimum value of DIT is 1.
 */
public class DIT {
	IJavaProject javaProject;
	private double metricValue;

	public double computeDIT(ICompilationUnit pClass, double pInizialization) {
		this.javaProject=pClass.getJavaProject();
		this.metricValue=pInizialization;


		IType type=pClass.getType(pClass.getElementName().substring(0, pClass.getElementName().length()-5));

		if(type.exists()) {
			try {
				if(type.getSuperclassName()!=null) {
					if(type.getSuperclassName().equals("Object"))
						return metricValue;

					this.metricValue++;
					ICompilationUnit cu=this.getClassByName(type.getSuperclassName());
					if(cu!=null) {
						this.computeDIT(cu, this.metricValue);
					} else return this.metricValue;
				}
			} catch (JavaModelException e) {
				e.printStackTrace();
			}
		}
		return this.metricValue;
	}

	private ICompilationUnit getClassByName(String pClassName) {
		try {
			for(IPackageFragment pack: this.javaProject.getPackageFragments()){
				for(ICompilationUnit cu: pack.getCompilationUnits()) {
					for(IType type: cu.getTypes()) {
						if(type.getElementName().equals(pClassName)) 
							return type.getCompilationUnit();
					}
				}
			}
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
		return null;
	}
}
