package ch.polgrabia.demos.client;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Verticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.http.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketSenderParticle extends AbstractVerticle {
  private static final Logger logger = LoggerFactory.getLogger(WebSocketSenderParticle.class);
  private final WebSocket webSocket;
  private MessageConsumer<Buffer> consumer;

  public WebSocketSenderParticle(WebSocket webSocket) {
    this.webSocket = webSocket;
  }

  @Override
  public void start() throws Exception {
    EventBus eventBus = getVertx().eventBus();
    this.consumer = eventBus.consumer(Constants.CLIENT_WEBSOCKET_SENDER_EVENTBUS_KEY, event -> {
      Buffer msg = event.body();
      logger.info("Sending binary message: {}", msg);
      webSocket.writeBinaryMessage(msg);
    });
  }

  @Override
  public void stop() throws Exception {
    consumer.unregister().result();
  }
}
