package eu.jonahbauer.wizard.server.socket;

import com.google.gson.JsonParseException;
import eu.jonahbauer.wizard.common.messages.client.ClientMessage;
import eu.jonahbauer.wizard.common.messages.server.NackMessage;
import eu.jonahbauer.wizard.server.NackException;
import eu.jonahbauer.wizard.server.machine.Player;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
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.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Log4j2
@Component
public class WizardSocketHandler extends TextWebSocketHandler {
    private final Map<String, Player> players = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(@NotNull WebSocketSession session) {
        var player = new Player(session);
        player.onOpen();

        players.put(session.getId(), player);
        log.info("Connection #{} from {}.", session.getId(), session.getRemoteAddress());
    }

    @Override
    protected void handleTextMessage(@NotNull WebSocketSession session, @NotNull TextMessage text) {
        var player = players.get(session.getId());
        try {
            player.onMessage(ClientMessage.parse(text.getPayload()));
        } catch (NackException e) {
            player.send(e.toMessage());
        } catch (JsonParseException e) {
            player.send(new NackMessage(NackMessage.MALFORMED_MESSAGE, "Could not parse " + text.getPayload() + "."));
        }
    }

    @Override
    public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus status) {
        players.get(session.getId()).onClose(status);
        log.info("Connection #{} closed {}.", session.getId(), status);
    }
}
