module Selftest {

import from General_Types all;
import from Osmocom_Types all;
import from GSM_Types all;
import from IPL4asp_Types all;
import from IPL4asp_PortType all;

import from BSSAP_Types all;
//import from BSSAP_Adapter all;
import from BSSAP_CodecPort all;
import from BSSMAP_Templates all;
import from IPA_Emulation all;
import from IPA_Types all;
import from RSL_Types all;

import from Osmocom_CTRL_Functions all;
import from Osmocom_CTRL_Types all;

import from MobileL3_CommonIE_Types all;
import from L3_Templates all;
import from GSM_RR_Types all;


type component IPA_selftest_CT {
	/* upper end of IPA_Emulation */
	port IPA_RSL_PT IPA_RSL;
	port IPA_CTRL_PT IPA_CTRL;
	port IPA_SP_PT IPA_SP;

	var IPA_Emulation_CT vc_IPA;

	/* raw IP port */
	port IPL4asp_PT IP;
	var ConnectionId g_ip_conn_id := -1;
}


function f_ipa_srv_init() runs on IPA_selftest_CT {
	vc_IPA := IPA_Emulation_CT.create("IPA_Emulation");
	map(vc_IPA:IPA_PORT, system: IPA_CODEC_PT);
	connect(vc_IPA:IPA_RSL_PORT, self:IPA_RSL);
	connect(vc_IPA:IPA_CTRL_PORT, self:IPA_CTRL);
	vc_IPA.start(IPA_Emulation.main_server("127.0.0.1", 55555));
}

function f_ipa_wait_up() runs on IPA_selftest_CT {
	interleave {
	[] IPA_RSL.receive(tr_ASP_IPA_EV(ASP_IPA_EVENT_UP));
	[] IPA_CTRL.receive(tr_ASP_IPA_EV(ASP_IPA_EVENT_UP));
	}
}

function f_tcp_client_init() runs on IPA_selftest_CT {
	var Result res;
	map(self:IP, system:IP);
	res := IPL4asp_PortType.f_IPL4_connect(IP, "127.0.0.1", 55555, "", -1,-1, {tcp:={}});
	if (not ispresent(res.connId)) {
		setverdict(fail, "Could not connect to TCP port, check your configuration");
		mtc.stop;
	}
	g_ip_conn_id := res.connId;
}


template ASP_Send ts_ASP_Send(ConnectionId id, template octetstring tx) := {
	connId := id,
	proto := omit,
	msg := tx
}

testcase TC_ipa_fragment() runs on IPA_selftest_CT {
	var integer i;
	var octetstring tx_buf;
	var RSL_Message rsl;

	f_ipa_srv_init();
	f_tcp_client_init();
	f_ipa_wait_up();

	rsl := valueof(ts_RSL_CHAN_RQD('23'O, 2342));
	tx_buf := enc_PDU_IPA(valueof(ts_PDU_IPA(IPAC_PROTO_RSL_TRX0, enc_RSL_Message(rsl))));
	/* send in rapid sequence to fill multiple messages in one TCP segment */
	for (i := 0; i < 10; i := i+1) {
		IP.send(ts_ASP_Send(g_ip_conn_id, tx_buf));
	}
	timer T:= 1.0;
	T.start;
	T.timeout;

	for (i := 0; i < 10; i := i+1) {
		IPA_RSL.receive(tr_ASP_RSL_UD(rsl));
	}
	setverdict(pass);
}


control {
	execute( TC_ipa_fragment() );
}


}
