package com.zcloud.personnel.positioning.websocket;

import com.zcloud.personnel.positioning.integration.realtime.RealtimeLocationPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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.ConcurrentWebSocketSessionDecorator;
import org.springframework.web.socket.handler.TextWebSocketHandler;

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

@Component
public class PersonLocationWebSocketHandler extends TextWebSocketHandler implements RealtimeLocationPublisher {
    private static final Logger LOGGER = LoggerFactory.getLogger(PersonLocationWebSocketHandler.class);

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final int sendTimeLimitMs;
    private final int bufferSizeLimitBytes;

    public PersonLocationWebSocketHandler(
            @Value("${personnel-positioning.websocket.location.send-time-limit-ms:10000}") int sendTimeLimitMs,
            @Value("${personnel-positioning.websocket.location.buffer-size-limit-bytes:524288}")
                    int bufferSizeLimitBytes) {
        this.sendTimeLimitMs = Math.max(1, sendTimeLimitMs);
        this.bufferSizeLimitBytes = Math.max(1024, bufferSizeLimitBytes);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        WebSocketSession concurrentSession = new ConcurrentWebSocketSessionDecorator(
                session, sendTimeLimitMs, bufferSizeLimitBytes);
        sessions.put(session.getId(), concurrentSession);
        LOGGER.info("Personnel location WebSocket connected, sessionId={}, connectionCount={}",
                session.getId(), sessions.size());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session.getId());
        LOGGER.info("Personnel location WebSocket disconnected, sessionId={}, status={}, connectionCount={}",
                session.getId(), status, sessions.size());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        removeAndClose(session.getId());
        LOGGER.warn("Personnel location WebSocket transport error, sessionId={}, connectionCount={}",
                session.getId(), sessions.size(), exception);
    }

    @Override
    public int publish(String payload) {
        TextMessage message = new TextMessage(payload);
        int delivered = 0;
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            WebSocketSession session = entry.getValue();
            if (!session.isOpen()) {
                sessions.remove(entry.getKey(), session);
                continue;
            }
            try {
                session.sendMessage(message);
                delivered++;
            } catch (Exception e) {
                removeAndClose(entry.getKey());
                LOGGER.warn("Failed to send personnel location, sessionId={}", entry.getKey(), e);
            }
        }
        return delivered;
    }

    int connectionCount() {
        return sessions.size();
    }

    private void removeAndClose(String sessionId) {
        WebSocketSession session = sessions.remove(sessionId);
        if (session == null || !session.isOpen()) {
            return;
        }
        try {
            session.close(CloseStatus.SERVER_ERROR);
        } catch (IOException e) {
            LOGGER.debug("Failed to close personnel location WebSocket, sessionId={}", sessionId, e);
        }
    }
}
