package com.yvan.mvc;

import com.yvan.PageDb;
import com.yvan.platform.Conv;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class PageDbResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.getParameterType() == PageDb.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        //offset=0 limit=10 page=1 rows=10
        //offset=10 limit=10 page=2 rows=10
        //offset=20 limit=10 page=3 rows=10
        //offset=60 limit=10 page=7 rows=10

        Object arg = webRequest.getParameter("offset");
        if (arg == null) {
            return new PageDb(false);
        }

        int limit = Conv.NI(webRequest.getParameter("limit"), 10);
        int page = Conv.NI(arg, 1)/limit + 1;
        return new PageDb(page, limit);
    }
}
