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

import com.atlassian.bitbucket.content.DiffContentFilter;
import com.sun.jersey.api.core.HttpContext;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Locale;

public class DiffContentFilterInjectable extends AbstractResourceInjectable<DiffContentFilter> {

    private static DiffContentFilter createFilter(String text, final boolean caseSensitive) {
        final String filter = caseSensitive ? text : text.toLowerCase(Locale.US);
        return new DiffContentFilter() {
            @Override
            public boolean apply(@Nonnull String input) {
                if (!caseSensitive) {
                    return input.toLowerCase(Locale.US).contains(filter);
                }
                return input.contains(filter);
            }
        };
    }

    @Override
    public DiffContentFilter doGetValue(HttpContext httpContext) {
        MultivaluedMap<String, String> queryParameters = httpContext.getRequest().getQueryParameters();
        String filter = StringUtils.trimToNull(queryParameters.getFirst("filter"));
        return filter != null ? createFilter(filter, "true".equalsIgnoreCase(queryParameters.getFirst("caseSensitive"))) : null;
    }
}
