package myservices;

import java.util.Iterator;
import java.util.List;

import org.eclipse.emf.ecore.EObject;

import fr.obeo.acceleo.ecore.factories.EFactory;
import fr.obeo.acceleo.ecore.factories.FactoryException;
import fr.obeo.acceleo.gen.template.eval.ENodeCastException;

public class MyServices {

	/**
	 * Used to easily determinate from which tagged values generated tag
	 * attributes, with identical name.
	 */

	public boolean contains(String target, String inThis) {
		return inThis.indexOf(target) != -1;
	}

	/**
	 * Used to cut the last boolean operations of a boolean expression. (Used
	 * when a boolean expression is generated from contributions.)
	 */

	public String fixExpressionEnd(String s) {
		if (s.endsWith(" || ")) {
			return s.substring(0, s.length() - 4);
		} else if (s.endsWith(" &amp;&amp; ")) {
			return s.substring(0, s.length() - 12);
		}
		return s;
	}

	/**
	 * Return the invers association end of a given associaton. (by Acceleo)
	 */
	public EObject inverseAssociationEnd(EObject object)
			throws FactoryException {
		EObject end = (EObject) object;
		Iterator it = ((List) EFactory.eGet((EObject) EFactory.eGet(object,
				"association"), "connection")).iterator();
		while (it.hasNext()) {
			EObject result = (EObject) it.next();
			if (result != end) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Return the String with the first letter uppercase. Useful for class name.
	 */
	public String firstUpper(String s) throws ENodeCastException {
		if (s.length() > 0)
			s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
		return s;
	}

	/**
	 * Return the String with the first letter lowercase. Useful for attribute
	 * name.
	 */
	public String firstLower(String s) throws ENodeCastException {
		if (s.length() > 0)
			s = Character.toLowerCase(s.charAt(0)) + s.substring(1);
		return s;
	}

	/**
	 * Removes the empty lines from the strings, thus if there is only empty 
	 * space between two new line characters then one new line character and the
	 * empty space is removed.
	 * This service is used by post operation on whole ADF generation template, and allows
	 * to write template that is much more readable, and easier understandable.
	 */
	
	public String removeEmptyLines(String s) {
		
		StringBuilder sb = new StringBuilder(s);
		int nl = -1;

		for (int i = s.length() - 1; i >= 0; i--) {
			char ch = s.charAt(i);
		
			if (nl != -1 && ch != '\n' && ch != '\t' && ch != ' ') {
				nl = -1;
				continue;
			} 
			
			if (sb.charAt(i) == '\n') {
				if (nl == -1) {
					nl = i;
				} else {
					sb.delete(i, nl);
					nl = i;
				}
			}
		}
		return sb.toString();
	}
	
}
