package com.wecloud.im.tillo.netty.handler;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wecloud.im.service.ImApplicationService;
import com.wecloud.im.service.ImClientService;
import com.wecloud.im.tillo.app_ws.AppImHandler;
import com.wecloud.im.tillo.app_ws.model.Constants;
import com.wecloud.im.tillo.app_ws.model.RequestHeaderConstants;
import com.wecloud.im.tillo.app_ws.utils.FullHttpRequestUtils;
import io.geekidea.springbootplus.framework.shiro.util.JwtUtil;
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.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Base64;
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;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private AppImHandler appImHandler;

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private ImApplicationService imApplicationService;

    /**
     * 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);

        DecodedJWT jwtInfo = JwtUtil.getJwtInfo(token);
        String payload = jwtInfo.getPayload();


        Base64.Decoder decoder = Base64.getDecoder();

        payload = new String(decoder.decode(payload), "UTF-8");


        JSONObject jsonObject = JSONObject.parseObject(payload);
        String appKey = (String) jsonObject.get("appKey");
        String id = (String) jsonObject.get("username");

//        redisTemplate.opsForValue().set("client:" + imApplication.getAppKey() + ":" + clientId, generateToken);


        // 设置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().addLast("appImHandler", appImHandler);



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

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

    }


}
