package com.ruoyi.cai.ws.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cai.chat.ChatManager;
import com.ruoyi.cai.ws.bean.FdCtxData;
import com.ruoyi.cai.ws.bean.Room;
import com.ruoyi.cai.ws.cache.FdCtxDataCache;
import com.ruoyi.cai.ws.constant.HangUpEnums;
import com.ruoyi.cai.ws.dto.WsToken;
import com.ruoyi.cai.ws.service.CheckConnectionDTO;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.util.WsExceptionUtil;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

/**
 * ws消息处理器统一入口
 */
@Component
public class MessageHandleApplication {

    @Autowired
    private Map<String,IMessageHandler> map;
    @Autowired
    private RoomService roomService;
    @Autowired
    private FdCtxDataCache fdCtxDataCache;
    @Autowired
    private ChatManager chatManager;

    public void processOn(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        if(StringUtil.isEmpty(payload)){
            return;
        }
        JSONObject jsonObject = JSON.parseObject(payload);
        Object method = jsonObject.get("method");
        if(method == null){
            return;
        }
        Map<String, Object> attributes = session.getAttributes();
        WsToken wsToken = chatManager.getToken(String.valueOf(attributes.get("token")));
        if(wsToken == null){
            WsExceptionUtil.throwExceptionFast(session,"无效token");
            return;
        }
        Long roomId = wsToken.getRoomId();
        Room room = roomService.load(roomId);
        if(room == null){
            WsExceptionUtil.throwException(session, "房间不可用" ,HangUpEnums.OTHER, roomId);
            return;
        }
        CheckConnectionDTO checkConnect = roomService.checkConnect(room);
        if(checkConnect != null){
            WsExceptionUtil.throwException(session,checkConnect.getMessage(),checkConnect.getHangUpEnums(),roomId);
            return;
        }
        IMessageHandler handler = map.get(String.valueOf(method));
        if(handler == null){
            return;
        }
        FdCtxData fdCtxData = fdCtxDataCache.getByRoomId(session.getId());
        handler.processOn(room,fdCtxData, jsonObject);

    }
}
