package com.usky.meeting.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
//@Component
public class MeetingDeviceWebSocketHandler extends TextWebSocketHandler {

    private static final Map<String, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();
    private static final Map<String, String> SESSION_DEVICE_MAP = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String sessionId = session.getId();
        String deviceCode = (String) session.getAttributes().get("deviceCode");
        SESSION_MAP.put(sessionId, session);
        if (deviceCode != null) {
            SESSION_DEVICE_MAP.put(sessionId, deviceCode);
        }
        log.info("WebSocket连接已建立, sessionId: {}, deviceCode: {}", sessionId, deviceCode);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到消息, sessionId: {}, message: {}", session.getId(), payload);
        String deviceCode = SESSION_DEVICE_MAP.get(session.getId());
        session.sendMessage(new TextMessage("{\"type\":\"ack\",\"deviceCode\":\"" + deviceCode + "\",\"message\":\"消息已收到\"}"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String sessionId = session.getId();
        SESSION_MAP.remove(sessionId);
        SESSION_DEVICE_MAP.remove(sessionId);
        log.info("WebSocket连接已关闭, sessionId: {}, status: {}", sessionId, status);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket传输错误, sessionId: {}", session.getId(), exception);
        if (session.isOpen()) {
            session.close();
        }
    }

    public static void sendMessage(String sessionId, String message) throws IOException {
        WebSocketSession session = SESSION_MAP.get(sessionId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }

    public static boolean isSessionOpen(String sessionId) {
        WebSocketSession session = SESSION_MAP.get(sessionId);
        return session != null && session.isOpen();
    }

    public static void removeSession(String sessionId) {
        SESSION_MAP.remove(sessionId);
        SESSION_DEVICE_MAP.remove(sessionId);
    }

    public static String getDeviceCodeBySession(String sessionId) {
        return SESSION_DEVICE_MAP.get(sessionId);
    }
}
