package org.elasticsearch.plugin.nlpcn;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import org.elasticsearch.rest.action.support.RestStatusToXContentListener;
import org.nlpcn.es4sql.SearchDao;

public class RestSqlAction extends BaseRestHandler {

	@Inject
	public RestSqlAction(Settings settings, Client client, RestController restController) {
		super(settings, restController, client);
		restController.registerHandler(RestRequest.Method.POST, "/_sql/_explain", this);
		restController.registerHandler(RestRequest.Method.GET, "/_sql/_explain", this);
		restController.registerHandler(RestRequest.Method.POST, "/_sql", this);
		restController.registerHandler(RestRequest.Method.GET, "/_sql", this);
	}

	@Override
	protected void handleRequest(RestRequest request, RestChannel channel, final Client client) throws Exception {

		String sql = request.param("sql");

		if (sql == null) {
			sql = request.content().toUtf8();
		}

		SearchDao searchDao = new SearchDao(client);
		ActionRequest actionRequest = searchDao.explain(sql).request();


		// TODO fix explain and add unit tests.
		if (request.path().endsWith("/_explain")) {
			BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, actionRequest.toString());
			channel.sendResponse(bytesRestResponse);
		} else {
			new ActionRequestExecuter(actionRequest, channel, client).execute();
		}
	}
}

@@ -392,16 +392,133 @@
 Inject;%0A
+import org.elasticsearch.common.io.stream.BytesStreamOutput;%0Aimport org.elasticsearch.common.io.stream.StreamOutput;%0A
 import o
@@ -1007,16 +1007,50 @@
 chDao;%0A%0A
+import java.io.FileOutputStream;%0A%0A
 public c
@@ -1839,16 +1839,23 @@
 nRequest
+Builder
  actionR
@@ -1860,16 +1860,23 @@
 nRequest
+Builder
  = searc
@@ -1892,16 +1892,70 @@
 ain(sql)
+;%0A%09%09ActionRequest actionRequest = actionRequestBuilder
 .request
@@ -1959,17 +1959,16 @@
 est();%0A%0A
-%0A
 %09%09// TOD
@@ -1973,32 +1973,16 @@
 ODO 
-fix explain and 
 add unit
  tes
@@ -1981,15 +1981,39 @@
 unit
- 
 tests
-.
+ to explain. (rest level?)
 %0A%09%09i
@@ -2146,16 +2146,23 @@
 nRequest
+Builder
 .toStrin

fix explain feature, fix bug explained in question #30