package org.testcontainers.containers;

import org.jetbrains.annotations.NotNull;
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

import static com.google.common.base.Strings.nullToEmpty;
import static java.lang.String.format;
import static java.time.temporal.ChronoUnit.SECONDS;

public class PrestoContainer<SELF extends PrestoContainer<SELF>> extends JdbcDatabaseContainer<SELF> {
    public static final String NAME = "presto";
    public static final String IMAGE = "prestosql/presto";
    public static final String DEFAULT_TAG = "329";

    public static final Integer PRESTO_PORT = 8080;

    private String username = "test";
    private String catalog = null;

    public PrestoContainer() {
        this(IMAGE + ":" + DEFAULT_TAG);
    }

    public PrestoContainer(final String dockerImageName) {
        super(dockerImageName);
        this.waitStrategy = new LogMessageWaitStrategy()
            .withRegEx(".*io.prestosql.server.PrestoServer\\s+======== SERVER STARTED ========.*")
            .withStartupTimeout(Duration.of(60, SECONDS));

        addExposedPort(PRESTO_PORT);
    }

    @NotNull
    @Override
    protected Set<Integer> getLivenessCheckPorts() {
        return new HashSet<>(getMappedPort(PRESTO_PORT));
    }

    @Override
    public String getDriverClassName() {
        return "io.prestosql.jdbc.PrestoDriver";
    }

    @Override
    public String getJdbcUrl() {
        return format("jdbc:presto://%s:%s/%s", getHost(), getMappedPort(PRESTO_PORT), nullToEmpty(catalog));
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getPassword() {
        return "";
    }

    @Override
    public String getDatabaseName() {
        return catalog;
    }

    @Override
    public String getTestQueryString() {
        return "SELECT count(*) FROM tpch.tiny.nation";
    }

    @Override
    public SELF withUsername(final String username) {
        this.username = username;
        return self();
    }

    /**
     * @deprecated This operation is not supported.
     */
    @Override
    @Deprecated
    public SELF withPassword(final String password) {
        // ignored, Presto does not support password authentication without TLS
        // TODO: make JDBCDriverTest not pass a password unconditionally and remove this method
        return self();
    }

    @Override
    public SELF withDatabaseName(String dbName) {
        this.catalog = dbName;
        return self();
    }

    public Connection createConnection() throws SQLException, NoDriverFoundException {
        return createConnection("");
    }
}

@@ -1083,44 +1083,8 @@
 (%22.*
-io.prestosql.server.PrestoServer%5C%5Cs+
 ====

Make WaitStrategy's regex in PrestoContainer work with newer image (#2992)