package io.vertx.mqtt.it;

import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.mqtt.MqttClient;
import io.vertx.mqtt.MqttClientOptions;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;

@RunWith(VertxUnitRunner.class)
public class MosquittoTest {

  @ClassRule
  public static GenericContainer<?> mosquitto = new FixedHostPortGenericContainer<>("eclipse-mosquitto:2.0.12")
    .withFixedExposedPort(1883, 1883)
    .withClasspathResourceMapping("it/mosquitto.conf", "/mosquitto/config/mosquitto.conf", BindMode.READ_ONLY)
    .waitingFor(Wait.forLogMessage(".*mosquitto .* running.*", 1));

  private Vertx vertx;

  @Before
  public void setUp() {
    vertx = Vertx.vertx();
  }

  @After
  public void tearDown(TestContext ctx) {
    vertx.close(ctx.asyncAssertSuccess());
  }

  @Test
  public void test(TestContext ctx) {
    MqttClient client = MqttClient.create(vertx, new MqttClientOptions().setAutoGeneratedClientId(true));
    client
      .connect(mosquitto.getMappedPort(1883), mosquitto.getContainerIpAddress(), ctx.asyncAssertSuccess(connection -> {
        ctx.assertEquals(connection.code(), MqttConnectReturnCode.CONNECTION_ACCEPTED);
        client.disconnect(ctx.asyncAssertSuccess());
      }));
  }
}
