package Detectors;

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

import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;

import Smells.LongMethod;
import Smells.SMELLTYPE;
import Smells.Smell;

public class LongMethodDector extends Detector {

	public LongMethodDector(IResource resource, CompilationUnit Punit) {
		super(resource, Punit);
	}

	public List<Smell> DetectSmells() {
		List types = unit.types();
		smells = new ArrayList<Smell>();
		for (Object obj : types) {
			if (!(obj instanceof TypeDeclaration))
				continue;
			TypeDeclaration typeDec = (TypeDeclaration) obj;
			DetectLongMethods(typeDec);
		}
		return smells;
	}

	private void DetectLongMethods(TypeDeclaration aType) {
		MethodDeclaration methods[] = aType.getMethods();
		for (MethodDeclaration method : methods) {                 //注意这条循环语句

			int length = method.getLength();
			int startPoint = method.getStartPosition();
			int lines = unit.getLineNumber(startPoint);
			lines = unit.getLineNumber(startPoint + length - 1) - lines;
//			printer.println("Method length: " + lines);
			if(lines<THRESHOLDS.getLONGMETHOD_LINES()) continue;
			Smell asmell = new LongMethod();
			//asmell.setType(SMELLTYPE.LONGMETHOD);
			asmell.resource = resource;
			asmell.unit = this.unit;
			asmell.associatedNode=method;
			asmell.setStartPoint(startPoint);
		    asmell.setLength(length);
		    asmell.explaination="The method "+method.getName()+"()"+" is a long method.";
			
			smells.add(asmell);
		}

	}
}
