

package pl.edu.pwr.nlprestservice;

import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import pl.edu.pwr.nlptools.NLPTool;
import pl.edu.pwr.nlptools.NLPToolException;

/**
 * REST Web Service
 *
 * @author www_zsk
 */
@Path("util")
public class Util {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of Synchro
     */
    public Util() {
    }

    
    private String sortbyFrequency(String nam)
    { String[] tab=nam.split("[\n?\r]");
      String res="";
      
       int[] count=new int[tab.length]; 
        for (int i=0;i<tab.length;i++ )
        {
            count[i]=1;
        }
        for (int i=0;i<tab.length;i++ )
           for (int j=i+1;j<tab.length;j++ )    
           {  if (i==j) continue;
              if (count[j]==0) continue;
               if (tab[i].equals(tab[j]))
               {  count[i]+=1;
                  count[j]=0; 
               }   
           }
        
        
        for (int i=tab.length-1;i>0;i-- )
             for (int j=0;j<tab.length;j++ )    
              if (count[j]==i && tab[j].length()>0)
              { 
                res+=tab[j]+"\n";
              }
        
        return res;
     }
    
    private String findNamedEntities(StringBuilder ccl) throws ParserConfigurationException, SAXException, IOException
    {  String result="";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                dbFactory.setValidating(false);
                dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
                DocumentBuilder dBuilder;
                dBuilder = dbFactory.newDocumentBuilder();
                
                //Document xml = dBuilder.parse(new String(sb).replace("<!DOCTYPE chunkList SYSTEM \"ccl.dtd\">", ""));
                   InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(new String(ccl)));

                Document xml = dBuilder.parse(is);
                NodeList chunks = xml.getElementsByTagName("chunk");
                
                for (int i=0;i<chunks.getLength();i++)
                { String prev="x";
                  Element chunk=(Element)chunks.item(i);
                  NodeList toks = chunk.getElementsByTagName("tok");
                  for (int i1=0;i1<toks.getLength();i1++)
                  { Element tok=(Element)toks.item(i1);
                     NodeList anns=tok.getElementsByTagName("ann");
                     for (int i2=0;i2<anns.getLength();i2++) 
                     { String idan=anns.item(i2).getTextContent();   
                                          
                       if (!idan.equals("0"))  
                     { idan=((Element)(anns.item(i2))).getAttribute("chan")+idan;
                       NodeList orths=tok.getElementsByTagName("base");
                       String base=((Element)orths.item(0)).getTextContent();
                       
                       if (prev.equals(idan))
                        result+=" "+base;
                       
                       else
                           result+="\n"+base;
                       prev=idan;
                     }
                     }
                  
        }
     }
                            return result;
    }
    
    private String getNamedEntities(String data)
    { 
          NLPTool nlpTool=new NLPTool("liner2");
          String id;
          String result="";
            try {
                id = nlpTool.saveText(data);
                id=nlpTool.processText(id);
                StringBuilder sb = nlpTool.readFile(id);
                return sortbyFrequency(findNamedEntities(sb));
                
            } catch (Exception ex) {
                throw new WebApplicationException(createResponse(ex, Response.Status.INTERNAL_SERVER_ERROR));
            }
          
       
        
        
    }
        @GET
	@Path("getNamedEntities/{data}")
        @Produces(MediaType.TEXT_PLAIN)
	public String getNamedEntitiesGet(@PathParam("data") String data)
        {  return getNamedEntities(data);
        }
        
        @POST
	@Path("getNamedEntities")
        @Produces(MediaType.TEXT_PLAIN)
	public String getNamedEntitiesPost( String data)
        {   return getNamedEntities(data);
        }
         @POST
        @Path("getNamedEntities")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_PLAIN)
    public String getNamedEntitiesMP(@FormParam("file") String data) 
    { 
        if (data==null) data=""; 
        return getNamedEntities(data);
    }  
        /* if exception message is provided, use it as it is;
     * if exception message is null, use fall back message 
     * (needs to be non-empty String in order to prevent 
     * HTTP container generated html message) */
    private Response createResponse(Exception ex, Response.Status status) {
        String message = ex.getMessage();
        if (message == null) {
            message = "Server internal error";
        }
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, message, ex);
        return Response.status(status).entity(message).type(MediaType.TEXT_PLAIN).build();
    }
}
