/**
 * @author      ETSI / STF481 / Yann Garcia
 * @version     $URL$
 *              $Id$
 */
package org.etsi.ttcn.codec.its.security;

import org.etsi.ttcn.codec.CodecBuffer;
import org.etsi.ttcn.codec.MainCodec;
import org.etsi.ttcn.codec.generic.Record;
import org.etsi.ttcn.common.ByteHelper;
import org.etsi.ttcn.tci.RecordValue;
import org.etsi.ttcn.tci.Type;

public class AcEnableSecurity extends Record {
    
    public AcEnableSecurity(MainCodec mainCodec) {
        super(mainCodec);
        setLengths();
    }

    private void setLengths() {
        mainCodec.setHint("Oct32", "32"); 
    }
    
    @Override
    protected void postEncodeField(String fieldName, CodecBuffer buf) {
//        System.out.println(">>> AcEnableSecurity.postEncodeField: " + fieldName);
        
        if (fieldName.equals("toBeSignedSecuredMessageTemplateDigest") || fieldName.equals("toBeSignedSecuredMessageTemplateCertificate")) {
//            System.out.println("AcEnableSecurity.postEncodeField: len=" + buf.getNbBytes());
            // Add length on 2 bytes
            CodecBuffer bufLen = new CodecBuffer(ByteHelper.intToByteArray(buf.getNbBytes(), Short.SIZE / Byte.SIZE));
            bufLen.append(buf);
            buf.overwriteWith(bufLen);
        }
    }
    
    @Override
    protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) {
//        System.out.println(">>> AcEnableSecurity.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName());
        
        if (fieldName.equals("toBeSignedSecuredMessageTemplateDigest") || fieldName.equals("toBeSignedSecuredMessageTemplateCertificate")) {
            // Extract length on 2 bytes
            int length = ByteHelper.byteArrayToInt(buf.readBits(Short.SIZE));
            mainCodec.setHint(decodingHypothesis.getName() + "Len", String.valueOf(length)); 
        }
    }
    
    @Override
    protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) {
//        System.out.println(">>> AcEnableSecurity.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName());
    }
    
} // End of class AcEnableSecurity
