/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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 {
    alias(libs.plugins.asciidoc)
    alias(libs.plugins.asciidoc.gems)
    id 'java-platform'
    id 'geb.publishing'
}

repositories {
    mavenCentral()
    ruby {
        gems()
    }
}

configurations {
    manual

    groovydocClasspath
    groovydocSources

    snippets
}

project(":module").subprojects.each { apiModule ->
    dependencies {
        groovydocClasspath project(path: apiModule.path)
        groovydocSources project(path: apiModule.path, configuration: "sources")
    }
}

dependencies {
    groovydocClasspath(project(":module:geb-core")) {
        capabilities {
            requireCapability("org.apache.groovy.geb:geb-core-select")
        }
    }

    asciidoctorGems("rubygems:asciidoctor-tabs:${libs.versions.asciidoctorTabs.get()}")

    snippets project(path: ":doc:manual-snippets", configuration: "allSources")
    snippets project(path: ":doc:manual-snippets:real-browser", configuration: "allSources")
    snippets project(path: ":module:geb-core", configuration: "allSources")
}

def snippetsDirectory = project.layout.buildDirectory.dir('snippets')
def snippetsPath= snippetsDirectory.get().asFile.absolutePath

def snippetsTask = tasks.register("snippets", Sync) {
    from configurations.snippets
    into snippetsDirectory

    include { fileTreeElement ->
        def file = fileTreeElement.file
        file.isDirectory() || file.withReader { reader ->
            reader.any { it.contains("tag::") }
        }
    }

    includeEmptyDirs = false
}

asciidoctorj {
    requires 'asciidoctor-tabs'
    options = [doctype: 'book']
    attributes = [
        toc                       : 'left',
        encoding                  : 'utf-8',
        'snippets-dir'            : snippetsPath,
        'snippets-res-dir'        : snippetsPath,
        'rb-snippets-dir'         : snippetsPath,
        'cm-snippets-dir'         : snippetsPath,
        'ct-snippets-dir'         : snippetsPath,
        numbered                  : true,
        sectlinks                 : true,
        idprefix                  : '',
        idseparator               : '-',
        icons                     : 'font',
        'source-highlighter'      : 'rouge',
        'geb-version'             : project.version,
        'geb-group'               : project.group,
        'geb-group-dir'           : project.group.replace('.', '/'),
        'spock-core-version'      : libs.versions.spock.get(),
        'selenium-version'        : libs.versions.selenium.get(),
        'htmlunit-driver-version' : libs.versions.htmlUnitDriver.get(),
        'groovy-version'          : libs.versions.groovy.get(),
        'sauce-connect-version'   : libs.versions.sauceConnect.get(),
        'home-page'               : 'groovy.apache.org/geb/',
        docinfo1                  : true,
        linkcss                   : true,
        stylesheet                : 'css/style.css',
        imagesdir                 : 'images',
        reproducible              : true,
        'tabs-sync-option'        : true,
        'tabs-sync-storage-key'   : 'tabs'
    ]

    modules {
        groovyDsl {
            version '2.0.2'
        }
    }

    docExtensions project(":doc:asciidoctor-extension")
}

def asciidoctorGemsPrepare = tasks.named("asciidoctorGemsPrepare") {
    foo().jvm {
        jvmArgs("--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED")
    }
}

tasks.named("asciidoctor") {
    jvm {
        jvmArgs("--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED")
    }

    sources {
        include 'index.adoc'
    }

    resources {
        from file('src/resources')
        from(asciidoctorGemsPrepare.map { new File(it.outputDir.get(), "gems/asciidoctor-tabs-${libs.versions.asciidoctorTabs.get()}/data/js/tabs.js") }) {
            rename { 'asciidoctor-tabs.js' }
        }
        from(asciidoctorGemsPrepare.map { new File (it.outputDir.get(), "gems/asciidoctor-tabs-${libs.versions.asciidoctorTabs.get()}/data/css/tabs.css") }) {
            rename { 'asciidoctor-tabs.css' }
        }
    }

    baseDirFollowsSourceDir()
    withGemJar(tasks.named('asciidoctorGemsJar'))

    inputs.files(snippetsTask)
        .withPathSensitivity(PathSensitivity.RELATIVE)
    inputs.files(asciidoctorGemsPrepare)
        .withPathSensitivity(PathSensitivity.RELATIVE)
}

def groovydocSourcesTask = tasks.register("groovydocSources", Sync) {
    inputs.files configurations.groovydocSources
    from({ configurations.groovydocSources.files.collect { zipTree(it) } })
    exclude 'META-INF/**'
    into project.layout.buildDirectory.dir('groovydocSources')
}

def apiDocTask = tasks.register("apiDoc", Groovydoc) {
    groovyClasspath = new GroovyRuntime(project) {}.inferGroovyClasspath(configurations.groovydocClasspath)
    classpath = configurations.groovydocClasspath
    destinationDir = project.layout.buildDirectory.dir('apiDoc').get().asFile
    source groovydocSourcesTask
    access = GroovydocAccess.PROTECTED
    processScripts = true
    includeAuthor = false
    includeMainForScripts = true
}

def packageManualTask = tasks.register("packageManual", Sync) {
    into project.layout.buildDirectory.dir('manual')
    from(asciidoctor, rootProject.layout.projectDirectory.files('LICENSE'))

    from(rootProject.layout.projectDirectory.dir('licenses')) {
        into 'licenses'
    }

    into("api") {
        from apiDocTask
    }

    includeEmptyDirs = false
}

def manualZipTask = tasks.register("manualZip", Zip) {
    from packageManualTask
    archiveBaseName = "geb-manual"
}

artifacts {
    manual(packageManualTask.map { it.outputs.files.singleFile }) {
        builtBy packageManualTask
    }
}

publishing {
    repositories {
        maven {
            name = "Apache"
            url = gebModule.isSnapshot()
                ? 'https://repository.apache.org/content/repositories/snapshots'
                : 'https://repository.apache.org/service/local/staging/deploy/maven2'
            credentials {
                username = gebModule.isSnapshot() ? findProperty('asfNexusUsername') : findProperty('apacheUser')
                password = gebModule.isSnapshot() ? findProperty('asfNexusPassword') : findProperty('apachePassword')
            }
        }
    }
    publications {
        manual(MavenPublication) {
            artifactId = 'geb-manual'
            artifact manualZipTask
            pom {
                name = "Geb Manual - The Book of Geb"
                description = "Geb (pronounced \"jeb\") manual, user guide and API reference."
            }
        }
    }
}

tasks.register("publishJarsAndManual") {
    dependsOn 'publishManualPublicationToApacheRepository'
}

tasks.register("openManual") {
    dependsOn "asciidoctor"
    doLast {
        new java.awt.Desktop().browse(fileTree(tasks.asciidoctor.outputDir).find { it.name == 'index.html' }.toURI())
    }
}
