package eu.dnetlib.enabling.tools.registration;

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

import javax.xml.ws.Endpoint;

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

import eu.dnetlib.enabling.is.lookup.ISLookUpServiceImpl;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;

/**
 * test ServiceRegistrationManagerImpl.
 *
 * @author marko
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class ServiceRegistrationManagerImplTest {

	/**
	 * fake profile.
	 */
	private static final String PROFILE = "<RESOURCE_PROFILE><HEADER><RESOURCE_KIND value=\"PendingServiceResources\"/></HEADER></RESOURCE_PROFILE>";

	/**
	 * instance under test.
	 */
	private transient ServiceRegistrationManagerImpl manager;

	/**
	 * registrator mock.
	 */
	@Mock
	private transient ServiceRegistrator registrator;

	/**
	 * is lookup mock.
	 */
	@Mock
	private transient ISLookUpService lookUpService;
	@Mock
	private UniqueServiceLocator serviceLocator;

	/**
	 * prepare.
	 *
	 * @throws ISLookUpException
	 *             cannot happen
	 */
	@Before
	public void setUp() throws ISLookUpException {
		manager = new ServiceRegistrationManagerImpl();
		manager.setServiceLocator(serviceLocator);
		manager.setRegistrator(registrator);
		manager.setService(new ISLookUpServiceImpl());

		when(serviceLocator.getService(ISLookUpService.class)).thenReturn(lookUpService);
		when(serviceLocator.getService(ISLookUpService.class, true)).thenReturn(lookUpService);
		when(lookUpService.getResourceProfile("123")).thenReturn(PROFILE);
		when(lookUpService.getResourceProfileByQuery(anyString())).thenReturn(PROFILE);
	}

	/**
	 * test state machine.
	 */
	@Test
	@Ignore
	public void testTick() {
		when(registrator.registerService(anyObject(), (Endpoint) anyObject())).thenReturn("123");

		assertEquals("check unregistered state", ServiceRegistrationManagerImpl.State.UNREGISTERED, manager.getState());
		manager.tick();
		assertEquals("check pending state", ServiceRegistrationManagerImpl.State.PENDING, manager.getState());
		assertEquals("ensure that the mock is correct", "PendingServiceResources", manager.getServiceProfile().getResourceKind());
		manager.tick();
		assertEquals("should remain pending", ServiceRegistrationManagerImpl.State.PENDING, manager.getState());

		manager.tick();
		assertEquals("should remain pending forever", ServiceRegistrationManagerImpl.State.PENDING, manager.getState());
	}

}
