/**
 * @author      ETSI / STF462 / Alexandre Berge
 * @version     $URL$
 *              $Id$
 */
package org.etsi.ttcn.codec.its.geonetworking;

import org.etsi.ttcn.codec.generic.Record;
import org.etsi.ttcn.codec.MainCodec;
import org.etsi.ttcn.codec.CodecBuffer;
import org.etsi.ttcn.codec.IMarkerCallback;

import org.etsi.ttcn.common.ByteHelper;
import org.etsi.ttcn.tci.EnumeratedValue;
import org.etsi.ttcn.tci.IntegerValue;
import org.etsi.ttcn.tci.RecordValue;
import org.etsi.ttcn.tci.Type;

public class CommonHeader extends Record implements IMarkerCallback {

    public CommonHeader(MainCodec mainCodec) {
        super(mainCodec);
    }

    @Override
    protected void postEncodeField(String fieldName, CodecBuffer buf) {

        if(fieldName.equals("plLength")) {
            buf.setMarker("plLength", 0, this);
        }
    }

    @Override
    protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) {

        if(fieldName.equals("nextHeader")) {
            int nh = ((EnumeratedValue)(rv.getField(fieldName))).getInt();
            mainCodec.setHint("GnNextHeader", Integer.toString(nh));
        }

        else if(fieldName.equals("plLength")) {
            int pl = ((IntegerValue)(rv.getField(fieldName))).getInt();
            mainCodec.setHint("payloadLength", Integer.toString(pl));
        }
    }

    @Override
    public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) {

        if(markerName.equals("plLength")) {
            int pl = java.lang.Integer.parseInt(mainCodec.getHint("payloadLength"));
            CodecBuffer preserveRightBuf = rightBuf.getBuffer(16, rightBuf.getNbBits() - 16);
            rightBuf.setBytes(ByteHelper.intToByteArray(pl, 2));
            rightBuf.append(preserveRightBuf);
        }
    }
}
