package com.ibiz.util.web;

import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.ibiz.util.SearchContext;

public class SearchContextHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return SearchContext.class.isAssignableFrom(parameter.getParameterType());
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		SearchContext searchContext = (SearchContext)parameter.getParameterType().newInstance();
		Map<String, String[]> params = webRequest.getParameterMap();
		
		PageableHandlerMethodArgumentResolver pageableResolver = new PageableHandlerMethodArgumentResolver();
		Pageable pageable = pageableResolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory) ;
		searchContext.setPageable(pageable);
		for (String key : params.keySet()) {
			if(key.equals("page")||key.equals("size")||key.equals("sort"))
				continue ;
			if(key.equals("query")){
				searchContext.setQuery(params.get(key)[0]);
				continue ;
			}
			searchContext.set(key, params.get(key)[0]);
		}
		return searchContext;
	}

}
