package org.mobicents.protocols.ss7.m3ua.impl;

import org.mobicents.protocols.ss7.m3ua.ExchangeType;
import org.mobicents.protocols.ss7.m3ua.Functionality;
import org.mobicents.protocols.ss7.m3ua.IPSPType;
import org.mobicents.protocols.ss7.m3ua.impl.fsm.FSM;
import org.mobicents.protocols.ss7.m3ua.message.MessageClass;
import org.mobicents.protocols.ss7.m3ua.message.MessageType;
import org.mobicents.protocols.ss7.m3ua.message.mgmt.Error;
import org.mobicents.protocols.ss7.m3ua.parameter.ErrorCode;
import org.mobicents.protocols.ss7.m3ua.parameter.RoutingContext;

/**
 * 
 * @author amit bhayani
 *
 */
public abstract class MessageHandler {

	protected AspFactory aspFactory = null;

	public MessageHandler(AspFactory aspFactory) {
		this.aspFactory = aspFactory;
	}

	protected void sendError(RoutingContext rc, ErrorCode errorCode) {
		Error error = (Error) this.aspFactory.messageFactory.createMessage(MessageClass.MANAGEMENT, MessageType.ERROR);
		error.setErrorCode(errorCode);
		if (rc != null) {
			error.setRoutingContext(rc);
		}
		this.aspFactory.write(error);
	}

	protected Asp getAspForNullRc() {
		// We know if null RC, ASP cannot be shared and AspFactory will
		// have only one ASP

		Asp asp = this.aspFactory.getAspList().get(0);

		if (asp.getAs().getRoutingContext() != null) {
			// verify that AS to which this ASP is added is also having null
			// RC.

			ErrorCode errorCodeObj = this.aspFactory.parameterFactory
					.createErrorCode(ErrorCode.Invalid_Routing_Context);
			sendError(null, errorCodeObj);
			return null;
		}

		return asp;
	}

	protected FSM getAspFSMForRxPayload(Asp asp) {
		FSM fsm = null;
		if (aspFactory.getFunctionality() == Functionality.AS
				|| (aspFactory.getFunctionality() == Functionality.SGW && aspFactory.getExchangeType() == ExchangeType.DE)
				|| (aspFactory.getFunctionality() == Functionality.IPSP && aspFactory.getExchangeType() == ExchangeType.DE)
				|| (aspFactory.getFunctionality() == Functionality.IPSP
						&& aspFactory.getExchangeType() == ExchangeType.SE && aspFactory.getIpspType() == IPSPType.CLIENT)) {
			fsm = asp.getLocalFSM();

		} else {
			fsm = asp.getPeerFSM();
		}

		return fsm;
	}

}

@@ -599,17 +599,18 @@
 ayani%0A *
+ 
 %0A
-
  */%0Apubl
@@ -1074,24 +1074,220 @@
 error);%0A%09%7D%0A%0A
+%09/**%0A%09 * Get's the ASP for any ASP Traffic Maintenance, Management, Signalling%0A%09 * Network Management and Transfer m3ua message's received which has null%0A%09 * Routing Context%0A%09 * %0A%09 * @return%0A%09 */%0A
 %09protected A
@@ -1459,47 +1459,47 @@
 if (
-asp.getAs().getRoutingContext() != null
+this.aspFactory.getAspList().size() %3E 1
 ) %7B%0A
@@ -1574,17 +1574,120 @@
 %09%09%09// RC
-.
+ or this asp is not shared by any other AS in which case we%0A%09%09%09// know messages are intended for same AS
 %0A%0A%09%09%09Err

fix for issue#3074 Make M3UA less stringent in terms of accepting M3UA messages without RC