package eu.dnetlib.enabling.resultset;

import static org.junit.Assert.*; // NOPMD
import static org.mockito.Mockito.*; // NOPMD

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import eu.dnetlib.enabling.resultset.rmi.ResultSetException;

/**
 * resultset service rmi implementation test.
 *  
 * @author marko
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class ResultSetServiceImplTest {

	/**
	 * mock resultset id.
	 */
	private static final String RS_ID = "123";

	/**
	 * instance under test.
	 */
	private transient ResultSetServiceImpl service;
	
	/**
	 * custom property dao mock.
	 */
	@Mock
	private transient ResultSetPropertyDao customPropertyDao;
	
	/**
	 * resultset registry mock. 
	 */
	@Mock
	private transient ResultSetRegistry resultsetRegistry;
	
	/**
	 * resultset instance mock. 
	 */
	@Mock
	private transient ResultSet resultSet;
	
	/**
	 * setup. 
	 */
	@Before
	public void setUp() {
		service = new ResultSetServiceImpl();
		service.setCustomPropertyDao(customPropertyDao);
		service.setResultsetRegistry(resultsetRegistry);
		
		when(resultsetRegistry.getResultSetById(RS_ID)).thenReturn(resultSet);
		when(resultSet.getIdentifier()).thenReturn(RS_ID);
	}

	/**
	 * test get property.
	 * @throws ResultSetException shouldn't happen
	 */
	@Test
	public void testGetProperty() throws ResultSetException {
		final Map<String, String> properties = new HashMap<String, String>();
		properties.put("prefetch", "true");
		
		when(customPropertyDao.getProperties(resultSet)).thenReturn(properties);
		when(resultSet.getNumberOfResults()).thenReturn(1);
		
		assertEquals("test builtin", "1", service.getProperty(RS_ID, "total"));
		assertEquals("test builtin", RS_ID, service.getProperty(RS_ID, "rsId"));
		
		assertEquals("test custom", "true", service.getProperty(RS_ID, "prefetch"));
		assertNull("test custom", service.getProperty(RS_ID, "unexistent"));
	}

	/**
	 * get resultset status.
	 * 
	 * @throws ResultSetException shouldn't happen
	 */
	@Test
	public void testGetRSStatus() throws ResultSetException {
		when(resultSet.isOpen()).thenReturn(true);
		
		assertEquals("check open", service.getRSStatus(RS_ID), "open");
		
		when(resultSet.isOpen()).thenReturn(false);
		assertEquals("check closed", service.getRSStatus(RS_ID), "closed");
	}

}
