package com.github.aesteve.vertx.nubes.utils.async;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

public class AsyncUtils {
	
	private static final Logger log = LoggerFactory.getLogger(AsyncUtils.class);
	
	public static<T> Handler<AsyncResult<T>> completeOrFail(Future<T> fut) {
		return (res -> {
			if (res.failed()) {
				fut.fail(res.cause());
			} else {
				fut.complete(res.result());
			}
		});
	}
	
	public static<T> Handler<AsyncResult<T>> completeFinally(Future<T> fut) {
		return (res -> {
			fut.complete();
		});
	}
	
	public static<T> Handler<AsyncResult<T>> ignoreResult(Future<Void> future) {
		return (res -> {
			if (res.failed()) {
				future.fail(res.cause()); 
			} else {
				future.complete();
			}
		});
	}

	public static<T> Handler<AsyncResult<T>> onSuccessOnly(NoArgHandler block) {
		return (res -> {
			if (res.failed()) {
				log.warn("Exception has been swallowed by AsyncUtils.onSuccess", res.cause());
				return;
			}
			block.handle();
		});
	}
	
	public static<T> Handler<AsyncResult<T>> onSuccessOnly(Handler<T> handler) {
		return (res -> {
			if (res.failed()) {
				log.warn("Exception has been swallowed by AsyncUtils.onSuccess", res.cause());
				return;
			}
			handler.handle(res.result());
		});
	}

	public static<T> Handler<AsyncResult<T>> onFailureOnly(Handler<T> handler) {
		return (res -> {
			if (res.failed()) {
				handler.handle(res.result());
			}
		});
	}

}

@@ -337,24 +337,154 @@
 class);%0D%0A%09%0D%0A
+%09public static%3CT%3E Handler%3CAsyncResult%3CT%3E%3E completeFinally(Future%3CT%3E fut) %7B%0D%0A%09%09return (res -%3E %7B%0D%0A%09%09%09fut.complete();%0D%0A%09%09%7D);%0D%0A%09%7D%0D%0A%09%0D%0A
 %09public stat
@@ -538,32 +538,32 @@
 ture%3CT%3E fut) %7B%0D%0A
-
 %09%09return (res -%3E
@@ -688,138 +688,8 @@
 %0A%09%0D%0A
-%09public static%3CT%3E Handler%3CAsyncResult%3CT%3E%3E completeFinally(Future%3CT%3E fut) %7B%0D%0A%09%09return (res -%3E %7B%0D%0A%09%09%09fut.complete();%0D%0A%09%09%7D);%0D%0A%09%7D%0D%0A%09%0D%0A
 %09pub
@@ -872,24 +872,24 @@
 omplete();%0D%0A
-
 %09%09%09%7D%0D%0A%09%09%7D);%0D
@@ -884,32 +884,274 @@
 %09%09%09%7D%0D%0A%09%09%7D);%0D%0A%09%7D%0D
+%0A%09%0D%0A%09public static%3CT%3E Handler%3CAsyncResult%3CT%3E%3E onSuccessOnly(Future%3CVoid%3E future, Handler%3CT%3E handler) %7B%0D%0A%09%09return (res -%3E %7B%0D%0A%09%09%09if (res.failed()) %7B%0D%0A%09%09%09%09future.fail(res.cause());%0D%0A%09%09%09%09return;%0D%0A%09%09%09%7D%0D%0A%09%09%09handler.handle(res.result());%0D%0A%09%09%7D);%0D%0A%09%7D%0D
 %0A%0D%0A%09public stati

add utilities