package jp.ac.osaka_u.sparql;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

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

    /**
     * Default constructor. 
     */
    public OffsetFind() {
    	super();
    }

	@Override
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		if (session == null){
			error(request, response, "init error");
			return;
		}
		EndpointSettings es = getEndpointSettings(request);
		if (es == null){
			error(request, response, "endpoint hasn't set");
			return;
		}

		OffsetManager om = (OffsetManager)session.getAttribute("offset");
		if (om == null){
			error(request, response, "session error");
			return;
		}
			
		String type = (String)request.getParameter("type");
		Integer offset = null;
		
		if (om.limit != null && om.offset != null){
			if (type.equals("next")){
				offset = new Integer(om.offset.intValue() + om.limit);
			} else if (type.equals("prev")){
				offset = new Integer(om.offset.intValue() - om.limit);
				if (offset.intValue() < 0){
					error(request, response, "offset error");
					return;
				}
			}
		}
		
		String json = null;
		json = new Finder().find(om.head, om.conditions, om.targetList, om.limit, offset, es);
		
		if (json != null){
			om.offset = offset;
			request.getSession(false).setAttribute("offset", om);
			response(request, response, json);
			
		} else {
			error(request, response, "json error");
		}

		
		
	}

}
