package eu.jonahbauer.wizard.server.debug;

import eu.jonahbauer.wizard.common.messages.ParseException;
import eu.jonahbauer.wizard.common.messages.observer.ObserverMessage;
import eu.jonahbauer.wizard.common.messages.server.NackMessage;
import eu.jonahbauer.wizard.common.messages.server.ServerMessage;
import eu.jonahbauer.wizard.common.model.Configuration;
import eu.jonahbauer.wizard.server.Lobby;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Profile;
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;

@Log4j2
@Component
@Profile("debug")
public class DebugSocketHandler extends TextWebSocketHandler {
    private final Map<String, DebugSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(@NotNull WebSocketSession session) {
        var dummySession = Lobby.getInstance().createDebugSession("Debug Session", 10, Configuration.DEFAULT);
        sessions.put(session.getId(), dummySession);

        log.info("Dummy connection #{} from {}.", session.getId(), session.getRemoteAddress());
    }

    @Override
    protected void handleTextMessage(@NotNull WebSocketSession session, @NotNull TextMessage text) throws IOException {
        var dummySession = sessions.get(session.getId());
        for (String line : text.getPayload().lines().toArray(String[]::new)) {
            try {
                dummySession.notify(ObserverMessage.parse(line));
            } catch (ParseException e) {
                try {
                    dummySession.notifyPlayers(ServerMessage.parse(line));
                } catch (ParseException e2) {
                    var nack = new NackMessage(NackMessage.MALFORMED_MESSAGE,"Could not parse " + text.getPayload() + ".").toString();
                    session.sendMessage(new TextMessage(nack));
                }
            }
        }
    }

    @Override
    public void afterConnectionClosed(@NotNull WebSocketSession session, @NotNull CloseStatus status) {
        var dummySession = sessions.get(session.getId());
        dummySession.close();
        Lobby.getInstance().removeSession(dummySession.getUuid());

        log.info("Dummy connection #{} closed {}.", session.getId(), status);
    }
}
