/*
 * Copyright 2019 - 2021 Aiven Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

plugins {

    // https://docs.gradle.org/current/userguide/java_library_plugin.html
    id "java-library"

    // https://docs.gradle.org/current/userguide/jacoco_plugin.html
    id "jacoco"

    // https://docs.gradle.org/current/userguide/distribution_plugin.html
    id "distribution"

    // https://docs.gradle.org/current/userguide/publishing_maven.html
    id "maven-publish"

    // https://docs.gradle.org/current/userguide/idea_plugin.html
    id 'idea'

    // https://plugins.gradle.org/plugin/com.diffplug.spotless
    id "com.diffplug.spotless" version "6.25.0"
}

wrapper {
    distributionType = 'ALL'
    doLast {
        final URI sha256Uri = new URI(wrapper.getDistributionUrl() + ".sha256")
        final String sha256Sum = new String(sha256Uri.toURL().bytes)
        wrapper.getPropertiesFile() << "distributionSha256Sum=${sha256Sum}\n"
        println "Added checksum to wrapper properties"
    }
}

repositories {
    mavenCentral()
}

spotless {
    format 'misc', {
        // define the files to apply `misc` to
        target '*.gradle', '*.md', '.gitignore'
        targetExclude ".*/**", "**/build/**", "**/.gradle/**"

        // define the steps to apply to those files
        trimTrailingWhitespace()
        indentWithSpaces()
        endWithNewline()
    }

    java {
        licenseHeaderFile file("${rootDir}/gradle-config/java.header")
        importOrder("javax", "java", "org.apache.kafka","org.opensearch","io.aiven","")
        removeUnusedImports()
        replaceRegex("No wildcard imports.", "import(?:\\s+static)?\\s+[^\\*\\s]+\\*;(\r\n|\r|\n)", '$1')
        eclipse().configFile("${rootDir}/gradle-config/aiven-eclipse-formatter.xml")
        indentWithSpaces()
        endWithNewline()
        trimTrailingWhitespace()
    }
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

compileJava {
    options.compilerArgs = ['-Xlint:all']
}

jacoco {
    toolVersion = "0.8.9"
}

distributions {
    main {
        contents {
            from jar
            from configurations.runtimeClasspath
        }
    }
}

publishing {
    publications {
        maven(MavenPublication) {
            // Defaults, for clarity
            groupId = getGroup()
            artifactId = getName()
            version = getVersion()

            pom {
                name = "Aiven's OpenSearch Connector for Apache Kafka"
                description = "Aiven's OpenSearch Connector for Apache Kafka"
                url = "https://aiven.io"
                organization {
                    name = "Aiven Oy"
                    url = "https://aiven.io"
                }
                licenses {
                    license {
                        name = "Apache License 2.0"
                        url = "http://www.apache.org/licenses/LICENSE-2.0.html"
                        distribution = "repo"

                    }
                }
                scm {
                    connection = "scm:git:git://github.com/aiven/aiven-kafka-connect-opensearch.git"
                    developerConnection = "scm:git:git@github.com:aiven/aiven-kafka-connect-opensearch.git"
                    url = "https://github.com/aiven/aiven-kafka-connect-opensearch.git"
                    tag = "HEAD"
                }
            }
        }
    }
}

ext {
    kafkaVersion = "3.8.1"
    apacheCommonsLangVersion = "3.18.0"
    slf4jVersion = "1.7.36"
    openSearchVersion = "2.19.3"

    mockitoVersion = "5.19.0"
    jacksonVersion = "2.18.2"

    junitVersion = "5.13.4"

    testcontainersVersion = "1.20.4"
}

sourceSets {
    integrationTest {
        java.srcDir file('src/integration-test/java')
        resources.srcDir file('src/integration-test/resources')
        compileClasspath += sourceSets.main.output + configurations.testRuntimeClasspath
        runtimeClasspath += output + compileClasspath
    }
}

idea {
    module {
        testSources = files(project.sourceSets.integrationTest.java.srcDirs)
        testSources = files(project.sourceSets.integrationTest.resources.srcDirs)
    }
}

configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntime.extendsFrom testRuntime
}

processResources {
    filesMatching('aiven-kafka-connect-opensearch-version.properties') {
        expand(version: version)
    }
}

dependencies {
    compileOnly "org.apache.kafka:connect-api:$kafkaVersion"
    compileOnly "org.apache.kafka:connect-json:$kafkaVersion"

    implementation "org.slf4j:slf4j-api:$slf4jVersion"
    implementation "com.google.code.gson:gson:2.13.1"
    implementation "org.opensearch.client:opensearch-rest-high-level-client:$openSearchVersion"
    implementation "org.apache.commons:commons-lang3:$apacheCommonsLangVersion"

    testImplementation platform("org.junit:junit-bom:${junitVersion}")
    testImplementation "org.junit.jupiter:junit-jupiter:${junitVersion}"

    testImplementation "org.mockito:mockito-core:${mockitoVersion}"
    testImplementation "org.mockito:mockito-junit-jupiter:${mockitoVersion}"

    testImplementation "org.apache.kafka:connect-api:$kafkaVersion"
    testImplementation "org.apache.kafka:connect-json:$kafkaVersion"
    testImplementation "com.fasterxml.jackson.core:jackson-core:${jacksonVersion}"
    testImplementation "com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}"
    testImplementation "com.fasterxml.jackson.core:jackson-annotations:${jacksonVersion}"

    testRuntimeOnly "org.slf4j:slf4j-log4j12:$slf4jVersion"
    testRuntimeOnly "org.junit.platform:junit-platform-launcher:1.13.4"

    integrationTestImplementation "org.testcontainers:junit-jupiter:$testcontainersVersion"
    integrationTestImplementation "org.testcontainers:kafka:$testcontainersVersion" // this is not Kafka version
    integrationTestImplementation "org.opensearch:opensearch-testcontainers:2.1.2"
    integrationTestImplementation "org.apache.kafka:kafka-clients:$kafkaVersion:test"
    integrationTestImplementation "org.apache.kafka:connect-runtime:${kafkaVersion}"
    integrationTestImplementation "org.apache.kafka:connect-runtime:${kafkaVersion}:test"
    integrationTestImplementation "org.apache.kafka:kafka_2.13:${kafkaVersion}"
    integrationTestImplementation "org.apache.kafka:kafka_2.13:${kafkaVersion}:test"
}

test {
    useJUnitPlatform {
        includeEngines 'junit-jupiter'
    }
}

task integrationTest(type: Test) {
    description = 'Runs the integration tests.'
    group = 'verification'
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath

    dependsOn test, distTar

    useJUnitPlatform()

    // Run always.
    outputs.upToDateWhen { false }

    // Pass the distribution file path to the tests.
    systemProperty("integration-test.distribution.file.path", distTar.archiveFile.get().asFile.path)
    systemProperty("opensearch.testcontainers.image-version",
        project.findProperty("opensearch.testcontainers.image-version") ? project.getProperty("opensearch.testcontainers.image-version") : "2.0.0")
}

task connectorConfigDoc {
    description = "Generates the connector's configuration documentation."
    group = "documentation"
    dependsOn "classes"

    doLast {
        javaexec {
            main = "io.aiven.kafka.connect.opensearch.OpensearchSinkConnectorConfig"
            classpath = sourceSets.main.runtimeClasspath + sourceSets.main.compileClasspath
            standardOutput = new FileOutputStream("$projectDir/docs/opensearch-sink-connector-config-options.rst")
        }
    }
}

tasks.named(JavaBasePlugin.CHECK_TASK_NAME) {
  dependsOn tasks.named('integrationTest')
}
