package com.gentics.mesh.util;

import com.gentics.mesh.core.rest.MeshEvent;
import com.gentics.mesh.etc.config.MeshOptions;
import com.gentics.mesh.event.MeshEventSender;
import com.gentics.mesh.parameter.ParameterProviderContext;
import io.reactivex.Completable;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class SearchWaitUtil {

	@Inject
	public MeshEventSender meshEventSender;

	@Inject
	public MeshOptions options;

	@Inject
	public SearchWaitUtil() {
	}


	public boolean delayRequested(ParameterProviderContext ppc) {
		return ppc.getSearchParameters().isWait()
				.orElseGet(options.getSearchOptions()::isWaitForIdle);
	}

	public Completable awaitSync(ParameterProviderContext ppc) {
		if (!delayRequested(ppc)) {
			return Completable.complete();
		}

		return meshEventSender.isSearchIdle().flatMapCompletable(isIdle -> {
			if (isIdle) {
				return Completable.complete();
			}
			meshEventSender.flushSearch();
			return meshEventSender.waitForEvent(MeshEvent.SEARCH_IDLE);
		}).andThen(meshEventSender.refreshSearch());
	}
}

@@ -118,16 +118,80 @@
 ptions;%0A
+import com.gentics.mesh.etc.config.search.ElasticSearchOptions;%0A
 import c
@@ -857,16 +857,241 @@
 );%0A%09%09%7D%0A%0A
+%09%09// We don't have to wait if no search is configured%0A%09%09ElasticSearchOptions searchOptions = options.getSearchOptions();%0A%09%09if (searchOptions == null %7C%7C searchOptions.getUrl() == null) %7B%0A%09%09%09return Completable.complete();%0A%09%09%7D%0A%0A
 %09%09return

Fix GraphQl if search is not configured