package org.atlasapi.query.common;

import static com.google.common.base.Preconditions.checkNotNull;

import javax.servlet.http.HttpServletRequest;

import org.atlasapi.query.annotation.ActiveAnnotations;
import org.atlasapi.query.annotation.AnnotationIndex;
import org.atlasapi.query.annotation.AnnotationsExtractor;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;

public class IndexAnnotationsExtractor implements AnnotationsExtractor {

    private static final String DEFAULT_PARAMETER_NAME = "annotations";

    private final AnnotationIndex lookup;
    private final String parameterName;

    private final Splitter csvSplitter = Splitter.on(",").omitEmptyStrings().trimResults();

    public IndexAnnotationsExtractor(AnnotationIndex lookup) {
        this(DEFAULT_PARAMETER_NAME, lookup);
    }

    public IndexAnnotationsExtractor(String parameterName, AnnotationIndex lookup) {
        this.parameterName = checkNotNull(parameterName);
        this.lookup = checkNotNull(lookup);
    }

    @Override
    public ActiveAnnotations extractFromSingleRequest(HttpServletRequest request)
            throws InvalidAnnotationException {

        String serialisedAnnotations = request.getParameter(parameterName);

        if (serialisedAnnotations == null) {
            return ActiveAnnotations.standard();
        }

        return lookup.resolveSingleContext(csvSplitter.split(serialisedAnnotations));
    }

    @Override
    public ActiveAnnotations extractFromListRequest(HttpServletRequest request)
            throws InvalidAnnotationException {
        
        String serialisedAnnotations = request.getParameter(parameterName);
        
        if (serialisedAnnotations == null) {
            return ActiveAnnotations.standard();
        }
        
        return lookup.resolveListContext(csvSplitter.split(serialisedAnnotations));
    }

    @Override
    public ImmutableSet<String> getParameterNames() {
        return ImmutableSet.of(parameterName);
    }
}

@@ -142,16 +142,64 @@
 quest;%0A%0A
+import com.google.common.collect.ImmutableList;%0A
 import o
@@ -1303,24 +1303,25 @@
 Name);%0A%0A
+%0A
         
 if (seri
@@ -1316,103 +1316,141 @@
     
-if (serialisedAnnotations == null) %7B%0A            return ActiveAnnotations.standard();%0A        %7D
+Iterable%3CString%3E annotations = serialisedAnnotations == null ? ImmutableList.%3CString%3Eof() : csvSplitter.split(serialisedAnnotations);
 %0A%0A  
@@ -1494,37 +1494,9 @@
 ext(
-csvSplitter.split(serialisedA
+a
 nnot
@@ -1494,33 +1494,32 @@
 ext(annotations)
-)
 ;%0A    %7D%0A%0A    @Ov

Fix bug when parsing annotations when no URL param is present.