package com.atlassian.stash.internal.rest.filter;

import com.atlassian.bitbucket.rest.comment.RestComment;
import com.atlassian.bitbucket.rest.enrich.MarkupEnricher;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

import java.util.List;

/**
 * Provides a {@code ContentResponseFilter} which detects the presence of markup-related query parameters on the
 * request and automatically converts text to html for certain instances in the entity graph (ie {@link RestComment}).
 */
public class MarkupResponseFilter implements ContainerResponseFilter {

    private final MarkupEnricher markupEnricher;

    public MarkupResponseFilter(MarkupEnricher markupEnricher) {
        this.markupEnricher = markupEnricher;
    }

    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        if (isQueryParamEnabled(request, "markup")) {
            response.setEntity(markupEnricher.enrich(response.getEntity()));
        }
        return response;
    }

    private boolean isQueryParamEnabled(ContainerRequest request, String key) {
        List<String> values = request.getQueryParameters().get(key);
        return values != null && values.size() > 0 && !values.contains("false");
    }
}
