package com.lona.tictactoe.web;

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.TextWebSocketHandler;

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

@Component
public class GameWebSocketHandler extends TextWebSocketHandler {

    @Value("${game.server.host:localhost}")
    private String serverHost;

    @Value("${game.server.port:1870}")
    private int serverPort;

    private final Map<WebSocketSession, TcpSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        TcpSession tcp = new TcpSession(session, serverHost, serverPort);
        sessions.put(session, tcp);
        tcp.start();
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        TcpSession tcp = sessions.get(session);
        if (tcp != null) {
            tcp.send(message.getPayload());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        TcpSession tcp = sessions.remove(session);
        if (tcp != null) {
            tcp.close();
        }
    }
}
