#include "DENMCodec.hh"
#include "Asn1cEncDec.hh"


int DENMCodec::encode (const LibItsDenm__TestSystem::DenmReq& req, OCTETSTRING& data)
{
	BITSTRING b;
	int rc = asnCodec.encode(req.msgOut(), b);
	if(rc){
		data = bit2oct(b);
	}
	return rc;
}

int DENMCodec::decode (const OCTETSTRING& data, LibItsDenm__TestSystem::DenmInd& ind)
{
	int rc = asnCodec.decode(oct2bit(data), ind.msgIn());
	if(rc) {
		/* TODO: fill other Indication fields */
	}
	return rc;
}

extern asn_TYPE_descriptor_t asn_DEF_DENM;

int DENMPDUCodec::encode (const DENM__PDU__Descriptions::DENM& denm, BITSTRING& data)
{
	int rc = -1;
	// encode as BER
	TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL,TTCN_EncDec::EB_WARNING);

	TTCN_Buffer ber_buf, per_buf;
	ber_buf.clear();
	per_buf.clear();

	//encode message in BER (CER variant, but can be any)
	denm.encode(DENM__PDU__Descriptions::DENM_descr_,ber_buf,TTCN_EncDec::CT_BER,BER_ENCODE_CER);

	// recode data as PER
	if( asn1c_ber2per(asn_DEF_DENM, ber_buf, per_buf) ) {
		rc = per_buf.get_len() * 8;
		data = BITSTRING(rc, per_buf.get_data());
	}
	return rc;
}

int DENMPDUCodec::decode (const BITSTRING& data, DENM__PDU__Descriptions::DENM& denm)
{
	// recode data to ber
	TTCN_Buffer per_buf, ber_buf;
	per_buf = TTCN_Buffer(bit2oct(data));
	ber_buf.clear();

	if(asn1c_per2ber(asn_DEF_DENM, per_buf, ber_buf)){
		ber_buf.rewind();
		denm.decode(DENM__PDU__Descriptions::DENM_descr_, ber_buf, TTCN_EncDec::CT_BER, BER_ACCEPT_ALL);
	}
	return per_buf.get_len();
}
