package de.hsadmin.processor;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

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

import de.hsadmin.core.qserv.Processor;
import de.hsadmin.core.qserv.ProcessorException;
import de.hsadmin.mods.cust.Customer;
import de.hsadmin.mods.pac.BasePac;
import de.hsadmin.mods.pac.Hive;
import de.hsadmin.mods.pac.Pac;
import de.hsadmin.mods.pac.PacProcessorFactory;

public class PacProcessor {

	private static EntityManagerFactory emFactory;
	private EntityManager entityManager;
	private PacProcessorFactory pacProcFactory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		emFactory = Persistence.createEntityManagerFactory("hsadmin");
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		emFactory.close();
	}

	@Before
	public void setUp() throws Exception {
		entityManager = emFactory.createEntityManager();
		pacProcFactory = new PacProcessorFactory();
	}

	@After
	public void tearDown() throws Exception {
		if (entityManager != null) {
			entityManager.close();
		}
	}

	@Test
	public void createCreateProcessor() {
		Customer cust = findCustomer("hsh00-hsh");
		assertNotNull(cust);
		BasePac basepac = findBasePacDW();
		assertNotNull(basepac);
		Hive hive = findHive("h99");
		assertNotNull(hive);
		try {
			Processor processor = pacProcFactory.createCreateProcessor(entityManager, new Pac("pac01", cust, basepac, hive));
			System.out.println(processor.toString());
		} catch (ProcessorException e) {
			fail(e.getMessage());
		}
	}

	private BasePac findBasePacDW() {
		Query basepacQuery = entityManager.createQuery("SELECT b FROM BasePacs b WHERE b.name = :basepacName AND b.valid = :valid");
		basepacQuery.setParameter("basepacName", "DW/B");
		basepacQuery.setParameter("valid", Boolean.TRUE);
		return (BasePac) basepacQuery.getSingleResult();
	}

	private Customer findCustomer(String name) {
		Query custQuery = entityManager.createQuery("SELECT c FROM Customers c WHERE c.name = :custName");
		custQuery.setParameter("custName", name);
		return (Customer) custQuery.getSingleResult();
	}

	private Hive findHive(String name) {
		Query hiveQuery = entityManager.createQuery("SELECT h FROM Hives h WHERE h.name = :hiveName");
		hiveQuery.setParameter("hiveName", name);
		return (Hive) hiveQuery.getSingleResult();
	}

	@Test
	public void createUpdateProcessor() {
		fail("Not yet implemented");
	}

	@Test
	public void createDeleteProcessor() {
		fail("Not yet implemented");
	}

}
