package com.xiaojukeji.know.streaming.test.container.mysql;

import com.xiaojukeji.know.streaming.km.persistence.utils.LoadSQLUtil;
import com.xiaojukeji.know.streaming.test.container.BaseTestContainer;
import org.jetbrains.annotations.NotNull;
import org.testcontainers.lifecycle.Startables;
import org.testcontainers.utility.DockerImageName;

import java.util.function.Supplier;

public class MySQLTestContainer extends BaseTestContainer {
    private static final String DB_USERNAME     = "root";
    private static final String DB_PASSWORD     = "1234567890";

    private static final String DATABASE_NAME   = "know_streaming";

    private static final String DB_PROPERTY     = "?useUnicode=true" +
            "&characterEncoding=utf8" +
            "&jdbcCompliantTruncation=true" +
            "&allowMultiQueries=true" +
            "&useSSL=false" +
            "&alwaysAutoGeneratedKeys=true" +
            "&serverTimezone=GMT%2B8" +
            "&allowPublicKeyRetrieval=true";

    private static final KSMySQLContainer<?> MYSQL_CONTAINER = new KSMySQLContainer<>(
            DockerImageName.parse("mysql:5.7").asCompatibleSubstituteFor("mysql")
    )
            .withEnv("TZ", "Asia/Shanghai")
            .withDatabaseName(DATABASE_NAME)
            .withUsername(DB_USERNAME)
            .withPassword(DB_PASSWORD)
            .addInitScriptPathAndContent(LoadSQLUtil.SQL_DDL_KS_KM, String.format("use %s;\n%s", DATABASE_NAME, LoadSQLUtil.loadSQL(LoadSQLUtil.SQL_DDL_KS_KM)))
            .addInitScriptPathAndContent(LoadSQLUtil.SQL_DDL_LOGI_JOB, String.format("use %s;\n%s", DATABASE_NAME, LoadSQLUtil.loadSQL(LoadSQLUtil.SQL_DDL_LOGI_JOB)))
            .addInitScriptPathAndContent(LoadSQLUtil.SQL_DDL_LOGI_SECURITY, String.format("use %s;\n%s", DATABASE_NAME, LoadSQLUtil.loadSQL(LoadSQLUtil.SQL_DDL_LOGI_SECURITY)))
            .addInitScriptPathAndContent(LoadSQLUtil.SQL_DML_KS_KM, String.format("use %s;\n%s", DATABASE_NAME, LoadSQLUtil.loadSQL(LoadSQLUtil.SQL_DML_KS_KM)))
            .addInitScriptPathAndContent(LoadSQLUtil.SQL_DML_LOGI, String.format("use %s;\n%s", DATABASE_NAME, LoadSQLUtil.loadSQL(LoadSQLUtil.SQL_DML_LOGI)))
            ;

    @NotNull
    public Supplier<Object> jdbcUsername() {
        return () -> DB_USERNAME;
    }

    @NotNull
    public Supplier<Object> jdbcPassword() {
        return () -> DB_PASSWORD;
    }

    @NotNull
    public Supplier<Object> jdbcUrl() {
        return () -> "jdbc:mariadb://"
                + MYSQL_CONTAINER.getHost() + ":" + MYSQL_CONTAINER.getMappedPort(3306)
                + "/" + DATABASE_NAME + DB_PROPERTY;
    }

    @Override
    public void init() {
        Startables.deepStart(MYSQL_CONTAINER).join();
    }

    @Override
    public void cleanup() {
    }
}
