package dst.ass1.jpa.examples;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.util.List;

import javax.persistence.EntityManager;

import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import dst.ass1.jpa.ORMService;
import dst.ass1.jpa.dao.ICoursePlatformDAO;
import dst.ass1.jpa.dao.IDAOFactory;
import dst.ass1.jpa.model.ICoursePlatform;
import dst.ass1.jpa.model.IModelFactory;

/**
 * This test has no test fixture and dependencies between tests. This is possible by declaring {@link ORMService} as a
 * static class-level rule via {@link ClassRule}.
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExampleTestWithDependencies {

    @ClassRule
    public static ORMService orm = new ORMService();

    @Test
    public void t01_insert() throws Exception {
        EntityManager em = orm.getEntityManager();
        IModelFactory modelFactory = orm.getModelFactory();

        ICoursePlatform cp1 = modelFactory.createCoursePlatform();
        cp1.setName("cp1");
        cp1.setUrl("http://cp1.example");

        ICoursePlatform cp2 = modelFactory.createCoursePlatform();
        cp2.setName("cp2");
        cp2.setUrl("http://cp1.example");

        em.persist(cp1);
        em.persist(cp2);

        em.getTransaction().begin();
        em.flush();
        em.getTransaction().commit();

        assertThat(cp1.getId(), notNullValue());
        assertThat(cp2.getId(), notNullValue());
    }

    @Test
    public void t02_query() throws Exception {
        IDAOFactory daoFactory = orm.getDaoFactory();
        ICoursePlatformDAO coursePlatformDAO = daoFactory.createCoursePlatformDAO();

        List<ICoursePlatform> all = coursePlatformDAO.findAll();

        assertThat(all.isEmpty(), is(false));
        assertThat(all.size(), is(2));

        System.out.println(all);
    }
}
