package eu.dnetlib.enabling.is.sn.resourcestate.hib;

import java.util.Collection;
import javax.annotation.Resource;

import eu.dnetlib.enabling.is.sn.resourcestate.AbstractResourceStateSubscriptionDAOImplTest;
import eu.dnetlib.enabling.is.sn.resourcestate.ResourceStateSubscription;
import eu.dnetlib.test.utils.EPRTestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

/**
 * test HibernateResourceStateSubscriptionDAOImplTest.
 * 
 * @author marko
 * 
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class HibernateResourceStateSubscriptionDAOImplTest extends AbstractResourceStateSubscriptionDAOImplTest {
	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(HibernateResourceStateSubscriptionDAOImplTest.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * instance under test.
	 */
	@Resource
	private transient HibernateResourceStateSubscriptionDAOImpl hibdao;

	/**
	 * cleanup db.
	 */
	@After
	public void tearDown() {
		final Collection<ResourceStateSubscription> subs = hibdao.listSubscriptions();
		if (subs != null) {
			subs.forEach(r -> hibdao.removeSubscription(r.getSubscriptionId()));
		}
	}

	/**
	 * test addition.
	 */
	@Test
	public void testAddSubscription() {
		assertNotNull("check dao", getDao());

		getDao().addSubscription(getSub());

		log.info("sub id: " + getSub().getSubscriptionId());
	}

	/**
	 * test encoding of endpoint references.
	 */
	@Test
	@DirtiesContext
	public void testEndpoint() {
		getSub().setSubscriber(EPRTestUtil.getTestEpr());

		getDao().addSubscription(getSub());

		final ResourceStateSubscription fresh = getDao().getSubscription(getSub().getSubscriptionId());

		assertNotNull("check", fresh);
		assertTrue("equals", compare(getSub(), fresh));

		assertNotNull("epr", getSub().getSubscriber());
		assertNotNull("fetched epr", fresh.getSubscriber());

		assertEquals("eprs", getSub().getSubscriber().toString(), fresh.getSubscriber().toString());
	}

	/**
	 * multiple subscriptions should not be allowed.
	 */
	@Test(expected = DataIntegrityViolationException.class)
	@DirtiesContext
	public void testMultiple() { // NOPMD
		getDao().addSubscription(getSub());
		getDao().addSubscription(getSub());
	}

	
	/**
	 * {@inheritDoc}
	 * 
	 * @see eu.dnetlib.enabling.is.sn.resourcestate.AbstractResourceStateSubscriptionDAOImplTest#prepareDao()
	 */
	@Override
	protected void prepareDao() {
		setDao(hibdao);
	}

}
