package antipatternsrecovery.antipatterns;

import java.util.Vector;

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

import antipatternsrecovery.beans.BeanConverter;
import antipatternsrecovery.beans.ClassBean;

public class ClassDataShouldBePrivate {
	private Vector<ClassBean> candidateClassDataShouldBePrivates;
	private IJavaProject projectToAnalyze;
	private int counterOfPublicFields;

	public ClassDataShouldBePrivate(IJavaProject pProject) {
		this.candidateClassDataShouldBePrivates=new Vector<ClassBean>();
		this.projectToAnalyze=pProject;
	}

	public Vector<ClassBean> searchClassDataShouldBePrivates(){
		try {
			for(IPackageFragment pack: this.projectToAnalyze.getPackageFragments()){
				for(ICompilationUnit cu: pack.getCompilationUnits()){
					for(IType type: cu.getTypes()) {
						this.counterOfPublicFields=0;
						int numberOfFields=0;
						if(type.getFields().length>3) {
							numberOfFields=type.getFields().length;
							for(IField field: type.getFields()){
								if(field.getSource().contains("public")){
									this.counterOfPublicFields++;
								}
							}
							if((this.counterOfPublicFields/numberOfFields) > 0.8) {
								ClassBean newClass=BeanConverter.softCastCUToClassBean(type.getCompilationUnit());
								if(! this.isIn(newClass))
									this.candidateClassDataShouldBePrivates.add(newClass);
							}
						}
					}
				}
			}
		} catch (JavaModelException e) {
			return this.candidateClassDataShouldBePrivates;
		}

		return this.candidateClassDataShouldBePrivates;
	}

	private boolean isIn(ClassBean pClassBean){
		for(ClassBean cb: this.candidateClassDataShouldBePrivates) {
			if(cb.getName().equals(pClassBean.getName()))
				return true;
		}
		return false;
	}

	public String toString() { 
		String toReturn="";
		for(ClassBean classBean: this.candidateClassDataShouldBePrivates){
			if(classBean.getBelongingPackage()!=null)
				toReturn+=classBean.getName()+"; " +classBean.getBelongingPackage().getName()+";\n";
			else 
				toReturn+=classBean.getName()+";\n";
		}
		return toReturn;
	}
}
