package chat;

import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

@Component
public class MyStompSessionHandler extends StompSessionHandlerAdapter {

    @Override
    public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
        session.subscribe("/topic/greetings", this);
        try {
            session.send("/app/hello", new HelloMessage("hello"));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    @Override
    public Type getPayloadType(StompHeaders headers) {
        return Greeting.class;
    }

    @Override
    public void handleFrame(StompHeaders headers, Object payload) {
        Greeting greeting = (Greeting) payload;
        MediatorService.greeting = greeting;
        MediatorService.countDownLatch.countDown();
        //System.out.println(greeting.getContent());
    }

    @Override
    public void handleException(StompSession s, StompCommand c, StompHeaders h, byte[] p, Throwable ex) {
        ex.printStackTrace();
    }

    @Override
    public void handleTransportError(StompSession session, Throwable ex) {
        ex.printStackTrace();
    }
}
