package controllers;

import java.util.*;

import play.*;
import play.mvc.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.libs.F.*;

import views.html.*;
import com.ociweb.JavaAddLib.*;

public class Application extends Controller {
  
	public static class AddParams {
		@Required public Integer x;
		@Required public Integer y;
	}

	static Result AddValues(final int x, final int y) {
		play.libs.F.Promise<List<String>> promise = play.libs.Akka.future(
				new java.util.concurrent.Callable<List<String>>() {
					public List<String> call() {
						String namingserviceHost = Play.application().configuration().getString("namingservice.host");
						Integer namingservicePort = Play.application().configuration().getInt("namingservice.port");
						List<String> response = new ArrayList<String>();
						
						try {
							AddClient c = new AddClient();
							c.init(namingservicePort, namingserviceHost);
				
							Vector<Ref> refs = c.list();
							if (refs.size() == 0) 
								response.add("No servers found");
							else {
								Iterator<Ref> it = refs.iterator();
							    while(it.hasNext()) {
							    	Ref r = it.next();
							    	String msg = r.Name + ": ";
							    	try {
							    		msg += c.add(r, x, y);
							    	} catch (Exception e) {
							    		msg += e.getMessage();
							    	}
							    	response.add(msg);
							    }
							}
						
							c.destroy();
						
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						return response;
					}
				}
				);
		return async(
				promise.map(
						new Function<List<String>,Result>() {
							public Result apply(List<String> response) {
								return ok(add.render(x,y,response));
							} 
						}
						)
				);
	}

	
	
  public static Result index() {
	    return ok(
		        index.render(form(AddParams.class))
		    );
  }
  
	public static Result doAdd() {
		Form<AddParams> form = form(AddParams.class).bindFromRequest();
		if (form.hasErrors()) {
		    return badRequest(index.render(form));
		} else {
		    AddParams data = form.get();
		    return AddValues(data.x,data.y);
		}

	}
  
}