package @app.group.id@.@app.name@.resources.support;

import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

public class HateoasPageableHandlerMethodArgumentResolver extends PageableHandlerMethodArgumentResolver {
    protected int defaultPageSize = 10;

    @Override
    public Pageable resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        String contentRange = webRequest.getHeader("Content-Range");
        if (contentRange != null && contentRange.length() > 0) {
            contentRange = contentRange.trim();
            if (contentRange.startsWith("item ")) {
                int index = contentRange.indexOf("/");
                String [] range = null;
                if (index > 0) {
                    range = contentRange.substring("item ".length(), index).split("-");
                } else {
                    range = contentRange.substring("item ".length()).split("-");
                }

                int from = Integer.parseInt(range [0]);
                int to = defaultPageSize;
                if (range.length > 1) {
                    to = Integer.parseInt(range [1]);
                }

                // Page size is never <= 0:
                int pageSize = Math.max(to - from + 1, 1);
                // Page is zero-based:
                int page = from / pageSize;

                return PageRequest.of(page, pageSize);
            }
        }

        return super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
    }
}
