package eu.dnetlib.enabling.tools;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;

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.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.tools.registration.ServiceNameResolver;
import eu.dnetlib.soap.cxf.StandaloneCxfEndpointReferenceBuilder;

/**
 * Test the dynamic service enumerator.
 *
 * @author marko
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class DynamicServiceEnumeratorTest {

	/**
	 * Dummy service interface.
	 *
	 * @author marko
	 *
	 */
	interface TestService {
	}

	/**
	 * instance under test.
	 */
	private transient DynamicServiceEnumerator<TestService> enumerator;

	/**
	 * lookup service locator mock
	 */
	@Mock
	private transient ISLookUpService lookUpService;

	/**
	 * lookup mock locator.
	 */
	private transient ServiceLocator<ISLookUpService> lookUpLocator;

	/**
	 * service name resolver mock.
	 */
	@Mock
	private transient ServiceNameResolver nameResolver;

	/**
	 * epr builder.
	 */
	StandaloneCxfEndpointReferenceBuilder eprBuilder;

	/**
	 * common preparation.
	 */
	@Before
	public void setUp()  {
		lookUpLocator = new StaticServiceLocator<ISLookUpService>(lookUpService);
		eprBuilder = new StandaloneCxfEndpointReferenceBuilder();

		enumerator = new DynamicServiceEnumerator<TestService>(TestService.class);
		enumerator.setLookUpLocator(lookUpLocator);
		enumerator.setServiceNameResolver(nameResolver);
		enumerator.setEprBuilder(eprBuilder);

		when(nameResolver.getName(TestService.class)).thenReturn("TestService");
	}

	/**
	 * test get services.
	 *
	 * @throws ISLookUpException mock exception
	 */
	@Test
	public void testGetServices() throws ISLookUpException {
		List<String> services = new ArrayList<String>();
		services.add("<service><id>123</id><url>http://test.com</url></service>");

		when(lookUpService.quickSearchProfile(anyString())).thenReturn(services);

		List<ServiceRunningInstance<TestService>> instances = enumerator.getServices();

		assertEquals("query size", 1, instances.size());
		assertEquals("service id", "123", instances.get(0).getServiceId());
		assertEquals("service url", "http://test.com", instances.get(0).getUrl());
		assertNotNull("service epr", instances.get(0).getEpr());
	}

	@Test
	public void testEmptyGetServices() throws ISLookUpException {
		List<String> services = new ArrayList<String>();
		when(lookUpService.quickSearchProfile(anyString())).thenReturn(services);

		List<ServiceRunningInstance<TestService>> instances = enumerator.getServices();
		assertTrue("empty", instances.isEmpty());
	}
}
