package emn.fr.ascola.extractor;
import java.util.Vector;

import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Modifier;


/**
 * Class for storing structure with full information.
 * @author jroyer
  */
public class Fields extends Vector<IVariableBinding> {
	
	/**
	 * Test if iv name exists in the fields.
	 * @param iv name
	 * TODO improve 
	 * @return
	 */
	public boolean containsKey(String iv) {
		for (IVariableBinding f : this) {
			if (iv.equals(f.getName())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Check if rectype is a type in the structure.
	 * used to verify communication boundaries
	 * @param rectype
	 * @return
	 */
	public boolean isInner(String rectype) {
		for (IVariableBinding f : this) {
			// check if right type name
			if (rectype.equals(f.getType().getBinaryName())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Merge the fields of the second to the first.
	 * Masking is taken into account 
	 * privates in other are discarded
	 * @param other
	 * @return
	 */
	public Fields merge(Fields other) {
		Fields result = new Fields();
		result.addAll(this);
		for (IVariableBinding f : other) {
			// same as Flags
			int mod = f.getModifiers();
			if (!Modifier.isPrivate(mod)) {
				String name = f.getName();
				if (!this.containsKey(name)) {
					result.add(f);
				}
			}
		}
		return result;
	}
	
	/**
	 * Filter the default-package fields.
	 * @return
	 */
	public Fields filter() {
		Fields result = new Fields();
		for (IVariableBinding f : this) {
			//f.getModifiers();
			if (f.getModifiers() != Flags.AccDefault) {
				result.add(f);
			}
		}
		return result;
	}
	
	/**
	 * Check if it has a public or default-package field.
	 * @return
	 */
	public boolean hasPublicFields() {
		boolean result = false;
		for (IVariableBinding f : this) {
			int m = f.getModifiers();
			if ((m == Flags.AccDefault) || (m == Flags.AccPublic)) {
				return true;
			}
		}
		return result;
	}
	
	/**
	 * String representation.
	 */
	public String toString() {
		String result = "[";
		for (IVariableBinding ivb : this) {
			result += ivb.getName()  + " : " + ivb.getType().getBinaryName()+ " ";
		}
		return result + "]";
	}

}
