package de.tblsoft.search.pipeline.filter.solr;

import de.tblsoft.search.pipeline.PipelineContainer;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.solr.client.solrj.SolrQuery;

import java.util.*;

/**
 * Created by tbl on 18.11.17.
 */
public class SolrParameterQueryTransformer implements QueryTransformerIF {

    private Map<String, List<String>> parameters;
    private Set<String> fieldList = new HashSet<>();

    @Override
    public SolrQuery transform(PipelineContainer pipelineContainer) {
        SolrQuery solrQuery = new SolrQuery();

        Map<String, String> replaceMap = new HashMap<>();

        synchronized (pipelineContainer.getRequest()) {
            Enumeration<String> parameterName = pipelineContainer.getRequest().getParameterNames();
            while (parameterName.hasMoreElements()) {
                String name = parameterName.nextElement();
                replaceMap.put(name, pipelineContainer.getRequest().getParameter(name));
            }
        }


        StrSubstitutor strSubstitutor = new StrSubstitutor(replaceMap);

        for(Map.Entry<String, List<String>> parameter: parameters.entrySet()) {
            for(String value: parameter.getValue()) {
                String replacedValue = strSubstitutor.replace(value);
                solrQuery.add(parameter.getKey(),replacedValue);
            }
        }

        for(String fieldName:fieldList) {
            solrQuery.addField(fieldName);
        }

        return solrQuery;
    }

    public void addParam(String name, String value){
        if(parameters == null) {
            parameters = new HashMap<>();
        }
        List<String> values = parameters.get(name);
        if(values == null) {
            values = new ArrayList<>();
        }
        values.add(value);
        parameters.put(name, values);
    }

    public void addFieldListValue(String fieldName) {
        fieldList.add(fieldName);


    }
}

@@ -196,16 +196,50 @@
 Query;%0A%0A
+import javax.servlet.http.Cookie;%0A
 import j
@@ -1019,16 +1019,722 @@
 name));%0A
+                replaceMap.put(%22query.%22 + name, pipelineContainer.getRequest().getParameter(name));%0A            %7D%0A%0A            Enumeration%3CString%3E headerNames =  pipelineContainer.getRequest().getHeaderNames();%0A            while (headerNames.hasMoreElements()) %7B%0A                String name = headerNames.nextElement();%0A                String value = pipelineContainer.getRequest().getHeader(name);%0A                replaceMap.put(%22header.%22 + name, value);%0A            %7D%0A%0A%0A            for(Cookie cookie : pipelineContainer.getRequest().getCookies()) %7B%0A                String name = cookie.getName();%0A                String value = cookie.getValue();%0A                replaceMap.put(%22cookie.%22 + name, value);%0A
         

allow the usage of header values and cookie values in the solr params