/**
 * 
 */
package anoncard;

import static org.junit.Assert.*;

import mixconfig.tools.dataretention.smartcard.ApduConstants;

import org.junit.Before;
import org.junit.Test;

import anoncard.util.Helpers;
import anoncard.util.ISOExceptionException;

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

	private Log log;

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		log = new Log();
	}

	/**
	 * Test method for {@link anoncard.Log#size()},
	 * {@link Log#addLogEntry(LogEntry)}, {@link Log#getLogEntry(short)} and
	 * {@link Log#reset()}.
	 */
	@Test
	public void testSize_AddLogEntry_GetLogEntry_Reset() {
		assertEquals(0, log.size());
		LogEntry[] logEntries = new LogEntry[4];
		assertTrue("Stupid test data", logEntries.length <= ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG);

		for (int i = 0; i < logEntries.length; i++) {
			byte[] messages = new byte[] { (byte) i, (byte) i };
			logEntries[i] = new LogEntry((byte) i, messages);

			log.addLogEntry(logEntries[i]);
			assertEquals(i + 1, log.size());

			LogEntry entry = log.getLogEntry((short) i);
			assertTrue("Couldn't read entry no " + i, entry != null);
			assertEquals(i, entry.getInstruction());
			assertArrayEquals(messages, Arrays.copyOf(entry.getData(), (short) 2, (short) (entry.getData().length - 2)));
		}
		assertEquals(null, log.getLogEntry((short) (logEntries.length + 1)));
		log.reset();
		assertEquals(0, log.size());
		assertEquals(null, log.getLogEntry((short) 0));
	}

	/**
	 * Test method for {@link anoncard.Log#isSpaceForOneMore()} and
	 * {@link Log#addLogEntry(LogEntry)}.
	 */
	@Test
	public void testIsSpaceForOneMore_AddLogEntry() {
		for (int i = 0; i < ApduConstants.MAXIMAL_SIZE_OF_ANONCARDAPPLET_LOG; i++) {
			assertTrue("There is space for more", log.isSpaceForOneMore());
			log.addLogEntry(new LogEntry((byte) i, new byte[] {}));
		}

		assertFalse("There is not space for more", log.isSpaceForOneMore());
		try {
			log.addLogEntry(new LogEntry((byte) 0, new byte[] {}));
			fail("Should cause Exception");
		} catch (ISOExceptionException e) {
			if (!Helpers.checkErrorCodeInException(e, ApduConstants.EXCEPTION_ANONCARDAPPLET_LOG_IS_FULL)) {
				fail(Helpers.alertResponseMismatch(e, ApduConstants.EXCEPTION_ANONCARDAPPLET_LOG_IS_FULL));
			}
		}

	}
}
