package com.k_int.discover.search.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


import org.apache.struts2.interceptor.ServletRequestAware;


import com.k_int.discover.sru.service.CollectionHierarchy;
import com.k_int.discover.sru.service.SearchDataService;
import com.opensymphony.xwork2.ActionSupport;

public class QueryBuilderAction extends ActionSupport implements
        ServletRequestAware
{
    
    private static final long serialVersionUID = 1L;
   
    private List<String> collectionRefinements                 = null;
    private List<String> sourceRefinements                     = null;
    private int numOfCollections                           = 0;
    private String selectedTextMatchCriteria               = "all";
    private List<String> typeRefinements                   = null;    
    private List<CollectionHierarchy> collectionHierarchy  = new ArrayList<CollectionHierarchy>();

    private String query_html="Your generated query will appear here";
    
    private CriteriaMapper[] matchCriteriaList = {
            new CriteriaMapper("all of these words", "all", false),
            new CriteriaMapper("at least one of these words", "any", true),
            new CriteriaMapper("the exact phrase", "exact", false)};


    // Variables for refining by type
    private TypeMapper[] resourceTypes         = {  new TypeMapper("image", "Image"), 
            new TypeMapper("video", "MovingImage"),
            new TypeMapper("audio", "Sound")};


    // Variables for refining where to search
    private FieldMapper[] fieldMatchList       = {  new FieldMapper("anywhere", "fullText"),
            new FieldMapper("in title & description.", "titleAndDesc"),
            new FieldMapper("in title", "dc.title"),
            new FieldMapper("in description", "dc.description")};
            //new FieldMapper("in subject", "dc.subject"),
            //new FieldMapper("in creator", "authority"),
            //new FieldMapper("in place", "place"),
            //new FieldMapper("in period", "dcterms.temporal")};

    // Variables for choosing the sample stylesheet to use
    private Map<String,String> stylesheets = new HashMap<String,String>();
    private String chosenStylesheet = "CG";
    private String[] possibleStylesheets = {"CG","Red","Blue"};
    
    
    private String matchFields;
    private boolean onlyThumbnails = true;
   
    private HttpServletRequest request;
    private SearchDataService dataService;
    
    
    public void setServletRequest(HttpServletRequest request)
    {
       this.request=request;
    }
    
    public void setDataService(SearchDataService dataService) {
        this.dataService = dataService;
    }
    
    public SearchDataService getDataService() {
        return this.dataService;
    }
    
    public int getNumOfCollections() {
        return this.numOfCollections;
    }
    
    public void setNumOfCollections(int num) {
        this.numOfCollections = num;
    }

    public void setCollectionRefinements(List<String> collectionRefinements) {
        this.collectionRefinements = collectionRefinements;
    }
    
    public void setSourceRefinements(List<String> sourceRefinements) {
        this.sourceRefinements = sourceRefinements;
    }
    
    public List<CollectionHierarchy> getCollectionHierarchy() {
        return this.collectionHierarchy;
    }
    
    public CriteriaMapper[] getMatchCriteriaList() {
        return this.matchCriteriaList;
    }
    
    public void setSelectedTextMatchCriteria(String value) {
        this.selectedTextMatchCriteria = value;
    }
    
    public TypeMapper[] getResourceTypes() {
        return this.resourceTypes;
    }
    
    public void setTypeRefinements(List<String> typeRefinements) {
        this.typeRefinements = typeRefinements;
    }

    
    public FieldMapper[] getFieldMatchList() {
        return this.fieldMatchList;
    }
    
    public void setMatchFields(String matchFields) {
        this.matchFields = matchFields;
    }

    public void setOnlyThumbnails(boolean onlyThumbnails) {
        this.onlyThumbnails = onlyThumbnails;
    }

    public boolean getOnlyThumbnails() {
        return this.onlyThumbnails;
    }
    
    public String getQueryHtml()
    {
        return query_html;
    }
    
    public String getMatchFields()
    {
        return matchFields;
    }
    
    public List<String> getTypeRefinements()
    {
        return typeRefinements;
    }
    
    public List<String> getCollectionRefinements()
    {
        return collectionRefinements;
    }
    
    public List<String> getSourceRefinements()
    {
        return sourceRefinements;
    }
    
    public String getSelectedTextMatchCriteria()
    {
        return selectedTextMatchCriteria;
    }
    
    public void setQueryHtml(String query_html)
    {
        this.query_html=query_html;
    }
    
    public String getChosenStylesheet() {
    	return this.chosenStylesheet;
    }
    
    public void setChosenStylesheet(String chosenStylesheet) {
    	this.chosenStylesheet = chosenStylesheet;
    }
    
    public String[] getPossibleStylesheets() {
    	return this.possibleStylesheets;
    }
    
    public String execute() throws Exception 
    {
		this.collectionHierarchy = this.getDataService().getAllCollectionsInHierarchy();

        // Set up the stylesheets
        this.stylesheets = new HashMap<String,String>();
    	this.stylesheets.put("Red", "http://www.culturegrid.org.uk/sru/xslt/red_sample.xsl");
    	this.stylesheets.put("Blue", "http://www.culturegrid.org.uk/sru/xslt/blue_sample.xsl");
        this.stylesheets.put("CG", "http://www.culturegrid.org.uk/sru/xslt/cg.xsl");
        
       
    	System.out.println("this.chosenStylesheet = " + this.chosenStylesheet);
    	System.out.println("this.stylesheets.get(chosenStylesheet) = " + this.stylesheets.get(this.chosenStylesheet));
    	
       // String submit = request.getParameter("pageSubmitted");
       
        if (request.getMethod().equals("POST")) 
        {
            StringBuffer buf = request.getRequestURL();
            String url = buf.toString();
            url=url.substring(0,url.length()-10);
            String full_url=url+"advanced";
            StringBuilder builder = new StringBuilder();
            builder.append("<form method=\"POST\" action=\"");
            //builder.append("http://");
            //builder.append(request.getServerName());
           // builder.append(":");
           // builder.append(request.getServerPort());
            builder.append(full_url);
            
            builder.append("\">\n");
            builder.append("<!-- startRecord controls the first result displayed -->\n");
            builder.append("<!-- i.e. it requires changing in the search request to page through results -->\n");
            builder.append("<input type=\"hidden\" name=\"stylesheet\" value=\"");
            builder.append(this.stylesheets.get(this.chosenStylesheet));
            builder.append("\" />\n");
            builder.append("<input type=\"hidden\" name=\"startRecord\"    value=\"1\" />\n");
            builder.append("<input type=\"hidden\" name=\"onlyThumbnails\" value=\"").append(this.onlyThumbnails).append("\"/>\n");
            builder.append("<input type=\"hidden\" name=\"x-facet\"    value=\"default\" />\n");
            builder.append("<input type=\"hidden\" name=\"matchFields\"  value=\"");
            builder.append(this.matchFields);
            builder.append("\"/>\n");
            if ( this.collectionRefinements != null && this.collectionRefinements.size() != 0) 
            {
                for (int i=0;i<collectionRefinements.size();i++)
                {
                    builder.append("<input type=\"hidden\" name=\"collectionRefinements\"  value=\"");
                    builder.append(collectionRefinements.get(i));
                    builder.append("\"/>\n");
                }
            }            
            
            if ( this.sourceRefinements != null && this.sourceRefinements.size() != 0) 
            {
                for (int i=0;i<sourceRefinements.size();i++)
                {
                    builder.append("<input type=\"hidden\" name=\"sourceRefinements\"  value=\"");
                    builder.append(sourceRefinements.get(i));
                    builder.append("\"/>\n");
                }
            } 
           
            builder.append("<input type=\"hidden\" name=\"selectedTextMatchCriteria\"  value=\"");
            builder.append(this.selectedTextMatchCriteria);
            builder.append("\"/>\n");
            
            if ( this.typeRefinements != null && this.typeRefinements.size() != 0) 
            {
                for (int i=0;i<typeRefinements.size();i++)
                {
                    builder.append("<input type=\"hidden\" name=\"typeRefinements\"  value=\"");
                    builder.append(typeRefinements.get(i));
                    builder.append("\"/>\n");
                }
            } 
            
            
            builder.append("<input type=\"text\" name=\"query\" value=\"\" id=\"advanced_query\"/>\n");   
            builder.append("<input name=\"go\" value=\"Search\" type=\"submit\" />");
            builder.append("</form>\n");
            query_html=builder.toString();
        }
        else
        {
            query_html="Your generated query will appear here";
            matchFields="fullText";
            selectedTextMatchCriteria="all";
            typeRefinements=new ArrayList<String>();
            collectionRefinements=new ArrayList<String>();
            sourceRefinements=new ArrayList<String>();
        }
        
        return "success";
    }
}
