/*
 * Copyright 2013-2016 Raffael Herzog, Marko Umek
 *
 * This file is part of markdown-doclet.
 *
 * markdown-doclet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * markdown-doclet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with markdown-doclet.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

// load local properties
File localPropertiesFile = new File(rootProject.projectDir, 'local.properties')
if (!localPropertiesFile.isFile()) {
    logger.warn "$localPropertiesFile does not exist or is not readable, build probably won't work"
}
logger.debug "Reading local properties from $localPropertiesFile"
localPropertiesFile.withReader('UTF-8') {
    def props = new Properties()
    def load = {String propName, boolean required ->
        def val = props[propName]
        if (val==null) {
            throw new GradleException("Property $propName not set. See README.build.md for instructions.")
        }
        logger.debug("[local.properties] $propName=$val")
        ext[propName] = val
    }
    props.load(it)
    load('jdk8.home', true)
    load('idea.home', true)
    load('jdk8.ideaName', true)
}

// some definitions
@SuppressWarnings("GroovyUnusedDeclaration") // it's used in subprojects
def toolsJar() {
    def path = "${rootProject.ext['jdk8.home']}/lib/tools.jar"
    def toolsJar = files(path)
    if (toolsJar.empty) throw new GradleException("$path not found")
    return toolsJar
}
def illegalAccessOpts = ['--add-opens=java.base/java.lang=ALL-UNNAMED', '--add-opens=java.base/java.lang.invoke=ALL-UNNAMED']
//noinspection GroovyAssignabilityCheck  --  I have no idea why this is needed, actually ...
def j8BootstrapClasspath = "${rootProject.ext['jdk8.home']}/jre/lib/rt.jar".with { path ->
    def bcp = files(path)
    if (bcp.empty) throw new GradleException("$it not found")
    return bcp
}

// project base
allprojects {
    def SNAPSHOT = '-SNAPSHOT'
    ext.componentVersion = { int version ->
        if ( project.version.endsWith(SNAPSHOT) ) {
            project.version = project.version.substring(0, project.version.length()-SNAPSHOT.length()) + '-' + version + SNAPSHOT
        } else {
            project.version = project.version.substring(0, project.version.length()-SNAPSHOT.length()) + '-' + version
        }
    }
    ext.snapshot = { boolean snapshot ->
        if ( snapshot && !project.version.endsWith(SNAPSHOT) ) {
            project.version = project.version + SNAPSHOT
        } else if ( !snaphsot && project.version.endsWith(SNAPSHOT) ) {
            project.version = project.version.substring(0, project.version.length() - SNAPSHOT.length())
        }
    }
    group = 'ch.raffael.markdown-doclet'
    buildDir = 'target'
}

allprojects {
    version = '2.0-SNAPSHOT'
    group = 'ch.raffael.markdown-doclet'
    buildDir = 'target'

    if ( !file('src').isDirectory() ) {
        return
    }

    apply plugin: 'java'
    apply plugin: 'groovy'
    apply plugin: 'idea'

    repositories {
        mavenLocal()
        jcenter()
    }

    dependencies {
        if ( path != ':nullity' ) {
            compileOnly project(':nullity')
        }
        testCompile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.15'
        testCompile('org.spockframework:spock-core:1.1-groovy-2.4') {
            exclude group: 'org.codehaus.groovy'
        }
        testCompile group: 'cglib', name: 'cglib-nodep', version: '3.1'
    }
    configurations { testCompile.extendsFrom compileOnly }

    sourceCompatibility = '8'
    archivesBaseName = "markdown-doclet"
    if ( project != rootProject ) {
        archivesBaseName += '-' + project.name
    }

    tasks.withType(JavaCompile).forEach {
        it.options.compilerArgs += [ '-proc:none', '-parameters' ]
    }
    tasks.withType(GroovyCompile).forEach {
        it.groovyOptions.fork = true
        it.groovyOptions.forkOptions.jvmArgs += illegalAccessOpts
        it.options.compilerArgs += [ '-proc:none', '-parameters' ]
    }

    javadoc.dependsOn classes
    afterEvaluate {
        javadoc {
            classpath += configurations.compileOnly
            options {
                locale 'en'
                docletpath = (sourceSets.main.output + sourceSets.main.compileClasspath) as List
                doclet = 'ch.raffael.mddoclet.MarkdownDoclet'
                def overviewFile = file('src/main/javadoc/overview.md')
                if ( overviewFile.exists() ) {
                    file('src/main/javadoc/overview.md')
                }
                linkSource = true
                links = [
                        'http://docs.oracle.com/javase/8/docs/api/',
//                        'http://docs.oracle.com/javase/8/docs/jdk/api/javadoc/doclet',
                ]
//                addStringOption 'javadocversion', 'v7'
                footer = """
              <a href="https://github.com/Abnaxos/markdown-doclet/" target="_top">
                <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub">
              </a>
              """
            }
        }
    }

    afterEvaluate {
        if (sourceCompatibility == JavaVersion.VERSION_1_8) {
            def j8homePropertyName = 'jdk8.home'
            def j8home = rootProject.ext."$j8homePropertyName"
            tasks.withType(Test) {
                it.executable = "$j8home${File.separator}bin${File.separator}java"
            }
            tasks.withType(JavaCompile).forEach {
                it.options.bootstrapClasspath = j8BootstrapClasspath
            }
            tasks.withType(GroovyCompile).forEach {
                it.options.bootstrapClasspath = j8BootstrapClasspath
            }
            idea.module {
                def ideaJdkPropertyName = 'jdk8.ideaName'
                if (rootProject.ext.properties.containsKey(ideaJdkPropertyName)) {
                    jdkName = rootProject.ext[ideaJdkPropertyName]
                } else {
                    logger.warn "Property '$ideaJdkPropertyName' not set, use 'local.properties' to set a v8 Java SDK."
                }
            }
        } else if (sourceCompatibility == JavaVersion.VERSION_1_9) {
            // do nothing for now
        } else {
            throw new GradleException("Unsupported source compatibility: $sourceCompatibility")
        }
    }

}
