/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.biohackathon.SPARQLBuilder.www;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.biohackathon.SPARQLBuilder.OWL.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import javax.json.Json;

/**
 *
 * @author atsuko
 */
@WebServlet(name = "SPServlet", urlPatterns = {"/sparql"})
public class SPServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SPServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SPServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
/*    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }*/
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        response.setContentType("application/json;charset=UTF-8");
	PrintWriter out = response.getWriter();
        String jpath = request.getParameter("jsonpath");
        Path path = null;
        try {
            path = convertJ2Path(jpath);
        } catch (JSONException ex) {
            Logger.getLogger(SPServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        String query = null;
        try {
            query = convertPath2SPARQL(path);
        } catch (Exception ex) {
            Logger.getLogger(SPServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        out.print(query);
    }

    

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Path convertJ2Path(String jpath) throws JSONException{
  
       JSONObject object = new JSONObject(jpath);
       String startClass = object.getJSONObject("startClassURI").toString();
       int width = Integer.parseInt(object.getJSONObject("width").toString());
       JSONArray classLinks = object.getJSONArray("classLinks");
        JSONObject jsonObject;
        List <ClassLink> list = null;
       
          for (int i=0;i<classLinks.length();i++) 
            {
            jsonObject = classLinks.getJSONObject(i);  
            String propertyURI = jsonObject.getJSONObject("propertyURI").toString();
            String linkedClassURI = jsonObject.getJSONObject("linkedClassURI").toString(); 
             String linkedLiteralDatatypeURI = jsonObject.getJSONObject("linkedLiteralDatatypeURI").toString(); 
            int numOfLinks = Integer.parseInt(jsonObject.getJSONObject("numOfLinks").toString());
            int numOfLinkedInstances = Integer.parseInt(jsonObject.getJSONObject("numOfLinkedInstances").toString()); 
            int numOfOriginInstances = Integer.parseInt(jsonObject.getJSONObject("numOfOriginInstances").toString());
            int numOfOriginClassInstances = Integer.parseInt(jsonObject.getJSONObject("numOfOriginInstances").toString());            
            int numOfLinkedClassInstances = Integer.parseInt(jsonObject.getJSONObject("numOfLinkedClassInstances").toString()); 
            
            ClassLink classLink =new ClassLink(propertyURI, linkedClassURI, linkedLiteralDatatypeURI, null, 
				 numOfLinks,  numOfOriginInstances,  numOfLinkedInstances,
				 numOfOriginClassInstances,  numOfLinkedClassInstances,
				false, false);
           list.add(classLink);
           }
          Path path = new Path(startClass,  list,  width);
          return path;
    }
  
    private String convertPath2SPARQL(Path path) throws Exception{
        if( path == null ){
			throw new Exception("Path is null.");
		}
		String startClass = path.getStartClass();
		List<ClassLink> classLinks = path.getClassLinks();
		
		StringBuffer queryStr = new StringBuffer();
		StringBuffer selStr = new StringBuffer();
		StringBuffer whereStr = new StringBuffer();
	//	if(num==0){
			int num = classLinks.size();
	//	}
			
		queryStr.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n");
		queryStr.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n");
				
		selStr.append("SELECT ");
		whereStr.append("WHERE { \n");

		String properties = null;
		String objectClasses = null;
		String subjectClasses = null;
		Direction direction = null;
		int i = 0;
		int k = 0;
		for (ClassLink link :classLinks )
		{
			properties = link.getPropertyURI();
			objectClasses = link.getLinkedClassURI();
			direction = link.getDirection();
			
			if (i==0)
		    subjectClasses = startClass;
			
			selStr.append("?c").append(i).append(" ");
			selStr.append("?l").append(i).append(" ");
			
			if(i == classLinks.size())
				selStr.append("\n");
			
			
			whereStr.append("?c").append(i).
			append(" rdf:type ").
			append("<").
			append(subjectClasses).
			append(">").
			append(".\n");
			
			whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");

						
			if(direction == Direction.forward)
			{
			whereStr.append("?c").append(i).append(" ");
			whereStr.append("<").append(properties).append("> ");			
			whereStr.append("?c").append(i+1).append(".\n");			
			}
			else
			{
				whereStr.append("?c").append(i+1).append(" ");
				whereStr.append("<").append(properties).append("> ");
				whereStr.append("?c").append(i).append(".\n");
			}
			
			subjectClasses = objectClasses;
			i++;
			k++;
			if(k>=num){
				break;
			}
		}
		
		selStr.append("?c").append(i).append(" \n");
		selStr.append("?l").append(i).append(" \n");
		whereStr.append("?c").append(i).append(" rdf:type ").
		    append("<").
		    append(subjectClasses).
		    append(">").
			append(".\n");
		whereStr.append("OPTIONAL{\n?c"+i+" rdfs:label ?l"+i+".}\n");
	
					
		queryStr.append(selStr).append(whereStr);
		
		queryStr.append("}");
		//OPTIONAL
		queryStr.append("LIMIT 100\n");;
		
		//System.out.println(queryStr);
		return queryStr.toString();
        
    
    }
}
