package sqlquery;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.alibaba.fastjson.JSONException;
import p2.p2server.P2Server;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;
import p2.ws.restful.WSRESTService;

@Path("/sqlquerydata")
public class SQLQueryWs implements WSRESTService {
	@GET
	@Produces({ "text/html" })
	@Consumes({ "text/xml" })
	public String getToken(@QueryParam("param") String param)
			throws JSONException, P2Exception {
		try {
			String param2 = param;
			param = new String(param.getBytes("iso8859-1"), "GBK");
			if (param.contains("?")) {
				param = param2;
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		param = param.substring(1, param.length() - 1);
		String[] params = param.split(";;;;");
		HashMap<String, String> map = new HashMap<String, String>(16);
		for (String a : params) {
			map.put(a.split("=")[0], a.split("=")[1]);
		}
		String reportname = map.get("SQLNAME");
		PaoSetRemote finereportset = P2Server.getP2Server().getPaoSet(
				"SQLQUERY", P2Server.getP2Server().getSystemUserInfo());
		finereportset.setWhere("SQLNAME='" + reportname + "'");
		finereportset.reset();
		String xml = "";
		if (finereportset.count() == 1) {
			sqlquery report = (sqlquery) finereportset.getPao(0);
			report.parammap = map;
			try {
				xml = report.runsql(true);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		finereportset.close();
		return xml;
	}

	@POST
	public String postToken(String param) throws JSONException, P2Exception {
		String[] params = param.split("&");
		HashMap<String, String> map = new HashMap<String, String>(16);
		for (String a : params) {
			if (a.split("=").length == 1) {
				map.put(a.split("=")[0], "");
			} else {
				map.put(a.split("=")[0], a.split("=")[1]);
			}
		}
		String reportname = map.get("SQLNAME");
		PaoSetRemote finereportset = P2Server.getP2Server().getPaoSet(
				"SQLQUERY", P2Server.getP2Server().getSystemUserInfo());
		finereportset.setWhere("SQLNAME='" + reportname + "'");
		finereportset.reset();

		String xml = "";
		if (finereportset.count() == 1) {
			sqlquery report = (sqlquery) finereportset.getPao(0);
			report.parammap = map;
			try {
				xml = report.runsql(true);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		finereportset.close();
		return xml;
	}
}
