package jp.ac.osaka_u.sparql;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.arnx.jsonic.JSON;

import jp.ac.osaka_u.sanken.sparql.EndpointSettings;

public abstract class ServletBase extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9062672737501676780L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected abstract void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

	
	protected void response(HttpServletRequest request, HttpServletResponse response, String json) throws ServletException, IOException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
		response.setHeader("Access-Control-Max-Age", "-1");
		String cb = (String)request.getParameter("callback");

		Map<String, String> ret = new HashMap<String, String>();
		ret.put("response", json);
		ret.put("sessionid", request.getSession().getId());
		
		response.setContentType("text/javascript; charset=UTF-8");
//		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(cb + "(" + JSON.encode(ret) + ")");
		out.flush();
	}
	
	protected void error(HttpServletRequest request, HttpServletResponse response, String word) throws ServletException, IOException{
		response(request, response, "{\"result\":\"" + word +"\"}");
	}
}
