// Copyright 1997 The Open Group Research Institute.  All rights reserved.

package krb5.lib;

import krb5.lib.asn1.*;

/**
 * Method data
 */
public class MethodData {

	/**
	 * Method type
	 */
	public int methodType;

	/**
	 * Method data 
	 */
	public byte[] methodData; //optional

	/**
	 * Class constructor
	 *
	 * @param ref is of type EncodeRef
	 * @exception Asn1Exception an exception
	 * @see krb5.lib.asn1.EncodeRef
	 * @see krb5.lib.Asn1Exception
	 */
	public MethodData(EncodeRef ref) throws Asn1Exception {
		EncodeRef subRef = decode.Sequence(ref);
		if (decode.Tag(subRef) == 0) {
			methodType = decode.Integer(subRef.startOfData());
			//XXX need to validate that the type is recognized
			subRef.next();
		}
		else
			throw new Asn1Exception(Krb5.ASN1_BAD_ID);
		if (decode.Tag(subRef) == 1) {
			methodData = decode.OctetString(subRef.startOfData());
			subRef.next();
		}
		if (subRef.isMoreInSequence())
			throw new Asn1Exception(Krb5.ASN1_BAD_ID);
	}

	/**
	 * Encodes the object in asn1
	 *
	 * @return byte[] is a result
	 * @exception Asn1Exception an exception
	 * @see krb5.lib.Asn1Exception
	 */
	public byte[] asn1Encode() throws Asn1Exception {
		if (methodData != null) {
			byte[][] method_data = {
				encode.prependExplicitTag(0, encode.Integer(methodType)),
				encode.prependExplicitTag(1, encode.OctetString(methodData))
			};
			return encode.Sequence(method_data);
		}
		else {
			byte[][] method_data = {
				encode.prependExplicitTag(0, encode.Integer(methodType)),
			};
			return encode.Sequence(method_data);
		}
	}

}