package com.ruoyi.cai.ws.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
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.service.CheckConnectionDTO;
import com.ruoyi.cai.ws.service.RoomService;
import com.ruoyi.cai.ws.util.MapGetUtil;
import com.ruoyi.cai.ws.util.WsExceptionUtil;
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;

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

    }
}
