package de.vfst.odb;

import static org.junit.Assert.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import de.vfst.odb.entities.Category;
import de.vfst.odb.entities.Ntt;

public class QueryWithEnumTest
{
	private static EntityManagerFactory entityManagerFactory;

	private EntityManager entityManager;

	@BeforeClass
	public static void setUpClass()
	{
		File dbdir = new File(System.getProperty("user.dir"));
		ODBSetup dbCreator = new ODBSetup();
		entityManagerFactory = dbCreator.setUpDB("QueryWithEnumTest", dbdir);
		EntityManager em = entityManagerFactory.createEntityManager();
		em.getTransaction().begin();
		em.persist(new Ntt("A", Category.ALPHA));
		em.persist(new Ntt("B", Category.BETA));
		em.persist(new Ntt("B2", Category.BETA));
		em.persist(new Ntt("C", Category.GAMMA));
		em.getTransaction().commit();
		em.close();
	}

	@Before
	public void setUp()
	{
		entityManager = entityManagerFactory.createEntityManager();
	}

	@After
	public void tearDown()
	{
		entityManager.close();
	}

	/**
	 * This test runs OK.
	 */
	@Test
	public void testGetBySingleEnum()
	{

		List<Ntt> nttList = entityManager.createNamedQuery(Ntt.LIST_BY_CATEGORY).setParameter("cat", Category.BETA)
				.getResultList();

		assertEquals(2, nttList.size());
	}

	/**
	 * This test fails but it should run OK --&gt; bug!
	 */
	@Test
	public void testGetBySingleEnumAsList()
	{

		List<Ntt> nttList = entityManager.createNamedQuery(Ntt.LIST_BY_CATEGORY_LIST)
				.setParameter("catlist", Category.BETA).getResultList();

		assertEquals(2, nttList.size());
	}

	/**
	 * This test runs OK, which is nice to have. Being strict it should fail with IllegalArgumentException.
	 */
	@Test
	public void testGetBySingleEnumAsString()
	{

		List<Ntt> nttList = entityManager.createNamedQuery(Ntt.LIST_BY_CATEGORY_LIST)
				.setParameter("catlist", Category.BETA.name()).getResultList();

		assertEquals(2, nttList.size());
	}

	/**
	 * This test fails which is correct following the spec. But it would be much nicer to have it running OK.
	 */
	@Test
	public void testGetByEnumListWithArray()
	{

		List<Ntt> nttList = entityManager.createNamedQuery(Ntt.LIST_BY_CATEGORY_LIST)
				.setParameter("catlist", new Category[]{Category.BETA }).getResultList();

		assertEquals(2, nttList.size());
	}

	/**
	 * This test fails which is correct following the spec. But it would be much nicer to have it running OK.
	 */
	@Test
	public void testGetByEnumListWithList()
	{
		List<Category> catlist = new ArrayList<Category>();
		catlist.add(Category.BETA);
		List<Ntt> nttList = entityManager.createNamedQuery(Ntt.LIST_BY_CATEGORY_LIST).setParameter("catlist", catlist)
				.getResultList();

		assertEquals(2, nttList.size());
	}

}
