package ch.polgrabia.demos.client;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketReceiverParticle extends AbstractVerticle {
  private static final Logger logger = LoggerFactory.getLogger(WebSocketReceiverParticle.class);
  private final WebSocket webSocket;
  private final String channel;
  private final Runnable onClose;

  public WebSocketReceiverParticle(WebSocket webSocket, String channel, Runnable onClose) {
    this.webSocket = webSocket;
    this.channel = channel;
    this.onClose = onClose;
  }

  @Override
  public void start() throws Exception {
    logger.info("Starting WebSocketReceiverParticle");
    webSocket
      .binaryMessageHandler(msg -> logger.info("[{}] Got message: {}", channel, msg))
      .closeHandler(unused -> {
        logger.info("[{}] Web socket is being closed {}", channel, webSocket.closeReason());
        try {
          onClose.run();
        } catch (Exception e) {
          logger.error("Got an error while stopping", e);
        }
      });
  }

}
