package com.ruoyi.cai.ws.handler;

import cn.hutool.core.util.URLUtil;
import com.google.common.base.Splitter;
import com.ruoyi.cai.chat.ChatManager;
import com.ruoyi.cai.ws.cache.FdCtxDataCache;
import com.ruoyi.cai.ws.constant.WebSocketConstants;
import com.ruoyi.cai.ws.holder.WebSocketSessionHolder;
import com.ruoyi.cai.ws.processon.OpenLogic;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.util.WebSocketUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.server.PathParam;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocketHandler 实现类
 *
 * @author zendwang
 */
@Slf4j
@Component
public class RoomWebSocketHandler extends AbstractWebSocketHandler {

    @Autowired
    private OpenLogic openLogic;
    @Autowired
    private MessageHandleApplication messageHandleApplication;
    /**
     * 连接成功后
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        URI uri = session.getUri();
        Map<String, String> para = getPara(uri == null ? null : uri.getQuery());
        Map<String, Object> attributes = session.getAttributes();
        attributes.putAll(para);
        openLogic.processOn(session);
        log.info("[connect] sessionId: {},userId:{}", session.getId(), session.getId());
    }

    private Map<String,String> getPara(String uri) {
        Map<String,String> map = new HashMap<>();
        if(StringUtils.isEmpty(uri)){
            return map;
        }
        String[] keys = uri.split("&");
        for (String key : keys) {
            String[] split = key.split("=");
            map.put(split[0],split.length > 1 ? split[1] : "");
        }
        return map;
    }

    /**
     * 处理发送来的文本消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        try {
            messageHandleApplication.processOn(session,message);
        }catch (Exception e){
            log.error("ws消息处理失败！需要开发检查问题!",e);
        }
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
    }

    /**
     * 心跳监测的回复
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        WebSocketUtils.sendPongMessage(session);
    }

    /**
     * 连接出错时
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("[transport error] sessionId: {} , exception:{}", session.getId(), exception.getMessage());
    }

    @Autowired
    private RoomService roomService;
    @Autowired
    private FdCtxDataCache fdCtxDataCache;
    /**
     * 连接关闭后
     *
     * @param session
     * @param status
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String token = String.valueOf(session.getAttributes().get("token"));
        // TODO 连接关闭 是否要删除fd的关系
        WebSocketSessionHolder.removeSession(token);
        log.info("[disconnect] sessionId: {},token:{}", session.getId(), token);
    }

    /**
     * 是否支持分片消息
     *
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}
