package tillo.app_ws.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.CharsetUtil;
import org.apache.http.MethodNotSupportedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import springfox.documentation.RequestHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.buffer.Unpooled.copiedBuffer;

/**
 * @Description netty请求工具类
 * @Author hewei hwei1233@163.com
 * @Date 2019-07-19
 */
public class FullHttpRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(RequestHandler.class);

    /**
     * 参数解析
     *
     * @param fullReq
     * @return
     * @throws MethodNotSupportedException
     */
    public static Map<String, String> parameterParse(FullHttpRequest fullReq) throws MethodNotSupportedException {
        HttpMethod method = fullReq.method();
        Map<String, String> parmMap = new HashMap<>(10);
        // GET请求
        if (HttpMethod.GET.equals(method) || HttpMethod.DELETE.equals(method)) {

            QueryStringDecoder decoder = new QueryStringDecoder(fullReq.uri());
            Map<String, List<String>> parameters = decoder.parameters();
            parameters.forEach((key, value) -> {
                // entry.getValue()是一个List, 只取第一个元素
                parmMap.put(key, value.get(0));
            });
        } else {
            // 不支持其它方法
            throw new MethodNotSupportedException("");
        }
        return parmMap;
    }

    /**
     * 获取body参数
     *
     * @param request
     * @return
     */
    public static String getBody(FullHttpRequest request) {
        ByteBuf buf = request.content();
        return buf.toString(CharsetUtil.UTF_8);
    }

    /**
     * 发送的返回值
     *
     * @param ctx     返回
     * @param context 消息
     * @param status  状态
     */
    public static void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=utf-8");

        logger.debug("response:\n" + response.toString() + "\ncontext:" + context);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
