package com.mx.cneeds.server.wechat.websocket.handler;

import com.alibaba.fastjson.JSON;
import com.mx.cneeds.server.wechat.common.dispatcher.MessageHandlerContainer;
import com.mx.cneeds.server.wechat.websocket.config.NettyChannelManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @ClassName OperateWebsocketHandler
 * @Author zzrdark
 * @Date 2020-06-23 16:11
 * @Description TODO
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class OperateWebsocketHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private NettyChannelManager nettyChannelManager;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest，处理参数
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap=getUrlParams(uri);


            System.out.println("接收到的参数是："+ JSON.toJSONString(paramMap));
            String wcId = null;
            if (paramMap.get("wcId") instanceof String){
                wcId = (String) paramMap.get("wcId");
            }

            // 增加用户信息
            nettyChannelManager.addUser(ctx.channel(),wcId);
            log.debug("服务端收到一个连接wcId为：{}",wcId);

            //如果url包含参数，需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }
            super.channelRead(ctx, msg);
        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;

            channelRead0(ctx,frame);
//            System.out.println("客户端收到服务器数据：" +frame.text());
        }

    }

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //ctx.channel().writeAndFlush(textWebSocketFrame);
    }

    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }
}
