package dst.ass1.jpa.examples;

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

import java.util.List;

import javax.persistence.EntityManager;

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

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

/**
 * This examples shows how you can write your own tests with custom fixtures that are injected it into the
 * {@link ORMService} rule. Using rules instead of abstract tests is considered good practice as it follows the
 * principle of composition over inheritance.
 */
public class ExampleTestWithCustomTestData {

    @Rule
    public ORMService orm = new ORMService(new MyTestData());

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

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

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

        System.out.println(all);
    }

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

        ICoursePlatform actual = coursePlatformDAO.findById(1L);

        assertThat(actual.getUrl(), is("http://cp1.example"));
    }

    public static class MyTestData implements ITestData {

        @Override
        public void insert(IModelFactory modelFactory, EntityManager em) {
            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.flush(); // transaction is done through the ORMTestFixture
        }
    }
}
