package com.huigou.topsun.sap.common.support;

import com.huigou.topsun.sap.common.domain.Message;
import com.huigou.topsun.sap.common.serializer.MessageDeserializer;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.stream.Collectors;

public class MessageHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private final static Logger LOG = LoggerFactory.getLogger(MessageHandlerMethodArgumentResolver.class);

    private MessageDeserializer messageDeserializer;

    public MessageHandlerMethodArgumentResolver(MessageDeserializer messageDeserializer) {
        this.messageDeserializer = messageDeserializer;
    }

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

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String requestText;
        try {
            requestText = IOUtils.readLines(webRequest.getNativeRequest(HttpServletRequest.class).getReader()).stream()
                    .collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            throw new IllegalArgumentException("解析SAP消息出错", ioe);
        }
        LOG.info("{},收到SAP消息: {}", parameter.getMethod().toString(), requestText);
        return messageDeserializer.deserialze(requestText);
    }

}
