/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.config;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.crunii.micro.common.spring.rest.RestBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.crunii.micro.web.interceptor.CallHolderInterceptor;
import com.crunii.micro.web.mvc.CurrWorkerMAR;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author 田平 create 2016年12月7日下午3:53:31
 */
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

	@Autowired(required = false)
	private CallHolderInterceptor holderInterceptor;

	@Resource(name = "objectMapper")
	private ObjectMapper objectMapper;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多个拦截器组成一个拦截器链
		// addPathPatterns 用于添加拦截规则
		// excludePathPatterns 用户排除拦截
		if (holderInterceptor != null) {
			registry.addInterceptor(holderInterceptor).addPathPatterns("/**");
		}

	}

	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		RestBuilder.addConverters(objectMapper,converters);
	}

	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		if (holderInterceptor != null) {
			argumentResolvers.add(new CurrWorkerMAR());
		}
	}
}
