// Copyright 1997 The Open Group Research Institute.  All rights reserved.

package krb4.lib;

import java.io.*;

public class Krb4APErr {
	public byte pvno;
	public byte msgType;
	boolean littleEndian;
	public int error_code;
	public String error_text;

	public Krb4APErr(
		int new_error_code,
		String new_error_text
	) {
		pvno = (byte)Krb4.KRB_PROT_VERSION;
		msgType = (byte)Krb4.AUTH_MSG_APPL_ERR;
		littleEndian = true;
		error_code = new_error_code;
		error_text = new_error_text;
	}

	public byte[] encode() throws Krb4Exception, IOException {
		ByteArrayOutputStream o = new ByteArrayOutputStream();
		o.write(pvno);
		byte temp = (byte)((msgType << 1) +
			(littleEndian ? 1 : 0));
		o.write(temp);
		o.write(Krb4Encode.toBytes(error_code));
		o.write(Krb4Encode.toBytes(error_text));
		return o.toByteArray();
	}

	public Krb4APErr(byte[] data) throws Krb4Exception {
		Krb4Encode ref = new Krb4Encode(data);
		pvno = ref.getByte();
		if (pvno != Krb4.KRB_PROT_VERSION)
			throw new Krb4Exception(Krb4.RD_AP_VERSION);
		byte temp = ref.getByte();
		msgType = (byte)(temp >>> 1);
		if (msgType != Krb4.AUTH_MSG_APPL_ERR)
			throw new Krb4Exception(Krb4.RD_AP_MSG_TYPE);
		littleEndian = (temp & 1) == 1;
		ref.setByteOrder(littleEndian);
		error_code = ref.getInt();
		error_text = ref.getString();
	}
}
