package com.sien.common.tillo.netty.handler;


import com.sien.common.tillo.app_ws.AppImHandler;
import com.sien.common.tillo.app_ws.model.Constants;
import com.sien.common.tillo.app_ws.model.RequestHeaderConstants;
import com.sien.common.tillo.app_ws.utils.FullHttpRequestUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Description 聊天模块 http请求处理
 * @Author hewei hwei1233@163.com
 * @Date 2019-07-19
 */
@Component
public class NettyApiRequest {
    private final Logger logger = LoggerFactory.getLogger(NettyApiRequest.class);

//    @Resource
//    private AppUserChannelsService appUserChannelsService;


    @Resource
    private AppImHandler appImHandler;

    /**
     * http请求接收
     *
     * @param ctx
     * @param msg
     * @param httpRequest
     * @throws Exception
     */
    public void handle(ChannelHandlerContext ctx, Object msg, FullHttpRequest httpRequest) throws Exception {
        if (!(msg instanceof FullHttpRequest)) {
            //                String context = JsonUtil.obj2Json(ResultModel.error(ResultStatus.REQUEST_ERROR));
            String context = "JsonUtil.obj2Json(ResultModel.error(ResultStatus.REQUEST_ERROR))";
            FullHttpRequestUtils.send(ctx, context, HttpResponseStatus.OK);
            return;
        }
        String path = httpRequest.uri();
        String body = FullHttpRequestUtils.getBody(httpRequest);


        if (logger.isDebugEnabled()) {
            logger.debug("httpRequest:\n" + httpRequest.toString() + "\n" + body);
        }

        if (path.contains(Constants.APP_WS_URL)) {
            /*
              app聊天http升级webSocket
             */
            this.initAppWs(ctx, httpRequest);

        }
    }


    /**
     * app 初始化websocket
     *
     * @param ctx
     * @param httpRequest
     * @throws org.apache.http.MethodNotSupportedException
     */
    private void initAppWs(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
        Map<String, String> paramMap = FullHttpRequestUtils.parameterParse(httpRequest);
        String token = paramMap.get(Constants.TOKEN);
        String deviceId = paramMap.get(RequestHeaderConstants.DEVICE_ID);
        String language = paramMap.get(RequestHeaderConstants.LANGUAGE);
        String platform = paramMap.get(RequestHeaderConstants.PLATFORM);

        // 当前版本号 VERSIONNO
        String versionNo = paramMap.get(RequestHeaderConstants.VERSION_NO);
        // 请求头userId
        String headerUserId = paramMap.get(RequestHeaderConstants.USER_ID);


        // 设置uri前缀
        httpRequest.setUri(Constants.APP_WS_URL);

        // 保持当前连接
        ctx.fireChannelRead(httpRequest.retain());

        // 设置属性值 userid - channel
//        ctx.channel().attr(AppUserChannelsService.USER_ID).set(userId);
//        ctx.channel().attr(AppUserChannelsService.LANGUAGE).set(language);

//         添加长连接handler
//        ctx.pipeline().addAfter("appWebSocketServerProtocolHandler","appImHandler", appImHandler);
        ctx.pipeline().addLast("appImHandler", appImHandler);



        // 保存用户上下文对象
//        appUserChannelsService.put(String.valueOf(headerUserId), (NioSocketChannel) ctx.channel());

        //移除当前api处理handler， 不再参与长连接处理
        ctx.pipeline().remove("SingleHttpRequestHandler");

    }


}
