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

import com.sun.jersey.api.model.AbstractMethod;
import com.sun.jersey.spi.container.*;

import java.util.Collections;
import java.util.List;

/**
 * A base class for creating {@code ResourceFilterFactory} implementations.
 */
public abstract class AbstractResourceFilterFactory implements ResourceFilterFactory {

    private final List<ResourceFilter> filters;

    public AbstractResourceFilterFactory(ContainerResponseFilter responseFilter) {
        filters = Collections.<ResourceFilter>singletonList(new ResourceFilterEx(responseFilter));
    }

    @Override
    public List<ResourceFilter> create(AbstractMethod am) {
        return filters;
    }

    private static class ResourceFilterEx implements ContainerResponseFilter, ResourceFilter {

        private final ContainerResponseFilter responseFilter;

        public ResourceFilterEx(ContainerResponseFilter responseFilter) {
            this.responseFilter = responseFilter;
        }

        @Override
        public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
            return responseFilter.filter(request, response);
        }

        /**
         * Always returns {@code null}. This filter does not apply to requests.
         *
         * @return {@code null}
         */
        @Override
        public ContainerRequestFilter getRequestFilter() {
            return null;
        }

        /**
         * Returns this filter.
         *
         * @return {@code this}
         */
        @Override
        public ContainerResponseFilter getResponseFilter() {
            return this;
        }
    }
}
