package jp.ac.osaka_u.sparql;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

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 jp.ac.osaka_u.sanken.sparql.EndpointSettings;
import jp.ac.osaka_u.sanken.sparql.SparqlAccessor;
import jp.ac.osaka_u.sanken.sparql.SparqlAccessorFactory;
import jp.ac.osaka_u.sanken.sparql.SparqlResultSet;

/**
 * Servlet implementation class Initialize
 */
public class Initialize extends ServletBase {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Initialize() {
        super();
    }

	@Override
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);

		init(request, response, session);
	}

	private void init(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
		EndpointSettings es = new EndpointSettings();
		es.setEndpoint((String)request.getParameter("endpoint"));
		es.setNamespaces((String)request.getParameter("namespaces"));
		String seed = UUID.randomUUID().toString();

		session.setAttribute(seed, es);

		boolean isOk = checkEndpoint(es);
		
System.out.println("session:["+session.getId()+"] ep:["+es.getEndpoint()+"]");
		response(request, response, "{\"seed\":\"" + seed + "\", \"result\":" + isOk + "}");

		
		
		
		return;

	}
	
	private boolean checkEndpoint(EndpointSettings es){
		SparqlAccessor sa = SparqlAccessorFactory.createSparqlAccessor(es);
		
		try {
			SparqlResultSet result = sa.find("select * {?s ?p ?o} LIMIT 1", 1);
			if (result.getDefaultResult() == null || result.getDefaultResult().size() == 0){
				return false;
			}
			return true;
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			return false;
		}

		
		
	}

}
