/*
 * This file has been developed at the University of Munich, Chair for Programming & Software Engineering.
 * 
 * This file is licensed under the Eclipse Public License (EPL) 1.0
 * 
 */
package eu.uml4soa.utbm.u2m.model;

import java.util.Arrays;
import java.util.List;


public class CTransition {

	private String fActionLabel;

	private CDirection fActionDirection;

	private CState fTo;

	private CState fFrom;

	private CTType fTransitionType;

	public CTransition(String actionName, CTType type, CDirection dir) {
		fActionLabel= actionName;
		fTransitionType= type;
		fActionDirection= dir;
	}

	public void renameTo(String newName) {
		String carriedName= getCarriedName();
		if (carriedName != null) {
			fActionLabel= newName + "(" + carriedName + ")";
		} else
			fActionLabel= newName;
	}

	public void setFrom(CState from) {
		fFrom= from;
	}

	public void setTo(CState to) {
		fTo= to;
	}

	public CState getFrom() {
		return fFrom;
	}

	public CState getTo() {
		return fTo;
	}

	public String getActionLabel() {
		return fActionLabel;
	}

	public CDirection getActionDirection() {
		return fActionDirection;
	}

	public CTType getTransitionType() {
		return fTransitionType;
	}

	@Override
	public String toString() {
		return fTransitionType.name() + " " + fActionLabel + " " + fActionDirection.name() + ": " + fFrom + " -> " + fTo;
	}

	public String getCarriedName() {
		int st= fActionLabel.indexOf("(");
		if (st == -1)
			return null;

		int en= fActionLabel.indexOf(")", st);
		if (en == -1)
			return null;

		return fActionLabel.substring(st + 1, en);
	}

	public boolean isThrow() {
		return getActionLabel().startsWith("throw");
	}

	/**
	 * Custom equals implementation.
	 * 
	 * @param cTransition
	 * @return
	 */
	public boolean isSameAs(CTransition cTransition) {
		if (cTransition == null)
			return false;

		return (cTransition.getFrom().getName().equals(getFrom().getName()) && cTransition.getTo().getName().equals(getTo().getName())
				&& cTransition.getActionLabel().equals(getActionLabel()) && cTransition.getTransitionType().equals(getTransitionType()) && cTransition
				.getActionDirection().equals(cTransition.getActionDirection()));
	}

	public String getReferencedActivity() {
		return getReferencedActivities().get(0);
	}

	public List<String> getReferencedActivities() {

		int start= getActionLabel().indexOf("(");
		int end= getActionLabel().indexOf(")");

		String names= getActionLabel().substring(start + 1, end);
		String[] split= names.split(",");

		return Arrays.asList(split);
	}


}
