/**
 * 
 */
package anoncard;

import javacard.framework.ISOException;
import mixconfig.tools.dataretention.smartcard.ApduConstants;

/**
 * @author christoph
 * 
 */
public class Log {

	/**
	 * The log entries.
	 */
	private LogEntry[] logEntries;

	/**
	 * The number of log entries.
	 */
	private short nextIndex;

	/**
	 * @param logEntries
	 * @param nextIndex
	 */
	public Log() {
		this.logEntries = new LogEntry[ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG];
		this.nextIndex = 0;
	}

	/**
	 * @return the size
	 */
	public short size() {
		return nextIndex;
	}

	/**
	 * Resets the log.
	 */
	public void reset() {
		this.logEntries = new LogEntry[ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG];
		this.nextIndex = 0;
	}

	/**
	 * Appends the logEntry at the log, or throws exception (
	 * {@link ApduConstants#EXCEPTION_ANONCARDAPPLET_LOG_IS_FULL}), iff the log
	 * is full.
	 * 
	 * @param logEntry
	 */
	public void addLogEntry(LogEntry logEntry) {
		if (isSpaceForOneMore()) {
			logEntries[nextIndex] = logEntry;
			nextIndex++;
		} else {
			ISOException.throwIt(ApduConstants.EXCEPTION_ANONCARDAPPLET_LOG_IS_FULL);
		}

	}

	/**
	 * Returns the indexTH logEntry, if there is any. Null otherwise.
	 * 
	 * @param index
	 * @return
	 */
	public LogEntry getLogEntry(short index) {
		if (0 <= index && index < ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG) {
			return logEntries[index];
		}
		return null;
	}

	/**
	 * 
	 * @return - true, iff {@link #nextIndex} <
	 *         {@link ApduConstants#MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG}.
	 */
	public boolean isSpaceForOneMore() {
		return (nextIndex < ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG);
	}
}
