package dst.ass1.jpa.tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

import javax.persistence.Query;

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

import dst.ass1.jpa.dao.IParticipantDAO;
import dst.ass1.jpa.model.IParticipant;
import dst.ass1.jpa.util.Constants;

public class Ass1_2_1aTest extends Ass1_TestBase {

    private IParticipantDAO dao;
    private Class<? extends IParticipant> entityClass;

    @Before
    public void setUp() throws Exception {
        dao = daoFactory.createParticipantDAO();
        entityClass = modelFactory.createParticipant().getClass();
    }

    @Test
    public void namedQuery_withEmailParameter_returnsNonEmptyResultSet() throws Exception {
        Query query = em.createNamedQuery(Constants.Q_PARTICIPANT_BY_EMAIL);

        try {
            query.setParameter("email", TestData.PARTICIPANT_1_EMAIL);
        } catch (IllegalArgumentException e) {
            throw new AssertionError("Could not set parameter 'email' in named query " + Constants.Q_PARTICIPANT_BY_EMAIL, e);
        }

        assertEquals("Expected exactly one result", 1, query.getResultList().size());
    }

    @Test
    public void findByEmail_returnsCorrectResult() throws Exception {
        Long participantId = testData.participant1Id;

        IParticipant actual = dao.findByEmail(TestData.PARTICIPANT_1_EMAIL);
        IParticipant expected = em.find(entityClass, participantId);

        assertEquals(participantId, actual.getId());
        assertSame(expected, actual); // note that they should actually be the same object due EntityManager caching!
    }

    @Test
    public void findByEmail_withNonExistingEmail_returnsNull() throws Exception {
        assertNull(dao.findByEmail("non@existing.com"));
    }
}
