package eu.dnetlib.enabling.tools.registration;

import static eu.dnetlib.enabling.tools.registration.ServiceRegistrationManagerImpl.State.PENDING;
import static eu.dnetlib.enabling.tools.registration.ServiceRegistrationManagerImpl.State.REGISTERED;

/**
 * This service registration manager implementation performs automatic service profile validation.
 * <p>
 * This is useful during automated testing. You can use it simply by overriding the default class in the service
 * registration manager bean template:
 * </p>
 *
 * <pre>
 * 	&lt;template:instance name=&quot;serviceRegistrationManager&quot;
 *  t:serviceRegistrationManagerClass=&quot;eu.dnetlib.enabling.tools.registration.ValidatingServiceRegistrationManagerImpl&quot;
 *  t:name=&quot;myServiceRegistrationManager&quot; t:service=&quot;myService&quot; t:endpoint=&quot;myServiceEndpoint&quot;
 *  t:jobScheduler=&quot;jobScheduler&quot;/&gt;
 * </pre>
 *
 * <p>
 * If your service needs to receive blackboard messages, the notification can be automatically subscribed to your
 * service profile simply by using a different service registrator component (blackboardServiceRegistrator):
 * </p>
 *
 * <pre>
 * 	&lt;template:instance name=&quot;serviceRegistrationManager&quot;
 *  t:serviceRegistrationManagerClass=&quot;eu.dnetlib.enabling.tools.registration.ValidatingServiceRegistrationManagerImpl&quot;
 *  t:name=&quot;myServiceRegistrationManager&quot; t:service=&quot;myService&quot; t:endpoint=&quot;myServiceEndpoint&quot;
 *  t:jobScheduler=&quot;jobScheduler&quot; t:serviceRegistrator=&quot;blackboardServiceRegistrator&quot;/&gt;
 * </pre>
 *
 * <p>
 * This option is very useful for example to the MDStoreService or the IndexService.
 * </p>
 *
 * @author marko
 *
 */
public class ValidatingServiceRegistrationManagerImpl extends ServiceRegistrationManagerImpl {
	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.tools.registration.ServiceRegistrationManagerImpl#tick()
	 */
	@Override
	public void tick() {
		synchronized (getRegistrator()) {
			if (getState() == PENDING) {
				if(getProfileId() == null) {
					throw new IllegalStateException("State is PENDING but profile id isn't initialized");
				}
				final String newId = getRegistrator().validateProfile(getProfileId(), getEndpoint());
				setProfileId(newId);
				setState(REGISTERED);
				return;
			}
		}

		super.tick();
	}

}
