package dst.ass1.jpa.tests;

import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.junit.Rule;
import org.junit.Test;

import dst.ass1.jpa.ORMService;
import dst.ass1.jpa.model.IMaterial;

public class Ass1_3_1Test {

    @Rule
    public ORMService orm = new ORMService();

    @Test
    public void entityListener_prePersistSetsPropertiesCorrectly() throws InterruptedException {
        Date then = new Date();
        Thread.sleep(50);

        EntityManager em = orm.getEntityManager();

        IMaterial material1 = orm.getModelFactory().createMaterial();

        material1.setUrn("material1");


        EntityTransaction tx;
        // persist
        tx = em.getTransaction();
        tx.begin();
        em.persist(material1);
        em.flush();
        tx.commit();

        assertNotNull(material1.getUploaded());
        assertNotNull(material1.getLastUpdate());

        assertThat(material1.getUploaded(), greaterThan(then));
        assertThat(material1.getLastUpdate(), greaterThan(then));
    }

    @Test
    public void entityListener_preUpdateSetsPropertiesCorrectly() throws InterruptedException {
        EntityManager em = orm.getEntityManager();

        IMaterial material1 = orm.getModelFactory().createMaterial();

        material1.setUrn("material1");

        EntityTransaction tx;
        // persist
        tx = em.getTransaction();
        tx.begin();
        em.persist(material1);
        em.flush();
        tx.commit();

        Date then = new Date();

        Thread.sleep(50);

        // update
        tx = em.getTransaction();
        tx.begin();
        material1.setType("sometype");
        em.persist(material1);
        em.flush();
        tx.commit();

        assertNotNull(material1.getLastUpdate());
        assertThat(material1.getLastUpdate(), greaterThan(then));
    }

}
