/*
 * Copyright (c) 2018 Ahome' Innovation Technologies. All rights reserved.
 *
 * 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.
 */

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath(group: 'org.ajoberstar', name: 'grgit', version: '1.7.2')
        classpath(group: 'commons-codec', name: 'commons-codec', version: '1.11')
        classpath(group: 'commons-logging', name: 'commons-logging', version: '1.2')
        classpath(group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.5')
        classpath(group: 'org.fusesource.jansi', name: 'jansi', version: '1.17')
        classpath(group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.15', classifier: 'indy')
    }
}

import org.apache.tools.ant.filters.FixCrLfFilter
import org.apache.tools.ant.filters.ReplaceTokens
import java.net.InetAddress
import org.ajoberstar.grgit.Grgit

apply plugin: 'pmd'
apply plugin: 'maven'
apply plugin: 'groovy'
apply plugin: 'signing'
apply plugin: 'eclipse'
apply plugin: 'findbugs'
apply plugin: 'checkstyle'

compileJava.options.encoding = 'UTF-8'

sourceCompatibility = 1.7

targetCompatibility = 1.7

version = '2.0.300-RELEASE'

group = 'com.ahome-it'

eclipse { classpath { downloadJavadoc = true } }

checkstyle {
    toolVersion = '7.7'
    ignoreFailures = true
}

tasks.withType(Checkstyle) { source 'src/main' }

pmd {
    ignoreFailures = true
    toolVersion = '5.6.1'
    ruleSets = [
        'java-basic',
        'java-braces',
        'java-empty',
        'java-imports',
        'java-optimizations',
        'java-strings',
        'java-unusedcode'
    ]
}

findbugs {
    ignoreFailures = true
    toolVersion = '3.0.1'
    effort = 'max'
}

tasks.withType(FindBugs) {
    reports {
        xml.enabled false
        html.enabled true
    }
}

task checkCodeQuality { doLast { println ':checkCodeQuality-done' } }

checkCodeQuality.dependsOn checkstyleMain,pmdMain,findbugsMain

task deleteConfigs(type: Delete) {
    project.fileTree(dir: "${buildDir}/resources/main").each { file ->
        file.delete()
    }
}

task filterConfigs(dependsOn: deleteConfigs, type: Copy) {
    from sourceSets.main.allSource
    into "${buildDir}/resources/main"
    filter(FixCrLfFilter)
    filter(ReplaceTokens, tokens: getFilterTokens())
}

task doJavaDocs(type: Groovydoc) {
    source = sourceSets.main.allSource
    classpath = sourceSets.main.runtimeClasspath + buildscript.configurations.classpath
    destinationDir = project.file("${buildDir}/docs/javadoc")
    includes = [
    	'com/ait/lienzo/**'
    ]
    docTitle = 'Lienzo 2D Structured Graphics'
    footer = "<small><a href=\"https://github.com/ahome-it/lienzo-core\" target=\"_blank\">Lienzo - ${getBuildModuleVersion()} - Author: Dean S. Jones</a></small>"
    getGroovydocLinks().each { name, list ->
        link(name, *list)
    }
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: doJavaDocs) {
    classifier = 'javadoc'
    from "${buildDir}/docs/javadoc"
}

compileJava.dependsOn(clean)

jar {
    manifest {
        attributes 'Implementation-Title': 'Lienzo-Core', 'Implementation-Version': getBuildModuleVersion()
    }
}

jar.dependsOn(filterConfigs)

def Map getFilterTokens() {
    [:]
}

def String getBuildModuleVersion() {
    version
}

def String getBuildDate() {
    (new Date()).toString()
}

def String getBuildServerHost() {
    try {
        InetAddress.getLocalHost().getHostName()
    }
    catch (Exception e) {
        'localhost'
    }
}

def String getJavaVersion() {
    System.getProperty('java.version') ?: 'unknown'
}

def String getBuildUser() {
    System.getProperty('user.name') ?: 'unknown'
}

def String getBuildServerBuild() {
    System.getenv('BUILD_DISPLAY_NAME') ?: "Gradle version ${gradle.gradleVersion}"
}

def String getBuildGITHomeURL() {
    'https://github.com/ahome-it/lienzo-core/' + getProjectArtifactID()
}

def String getBuildGITCommitHash() {
    getBuildGITHomeURL() + '/commit/' + Grgit.open(project.file('.')).head().id
}

def String getBuildGITCommitUser() {
    Grgit.open(project.file('.')).head().committer.email
}

def String getBuildGITCommitMessage() {
    Grgit.open(project.file('.')).head().shortMessage
}

repositories { mavenCentral() }

sourceSets {
    main { resources { source java } }
}

dependencies {
    compile(group: 'com.ahome-it', name: 'ahome-tooling-nativetools', version: '1.0.195-RELEASE')
    compileOnly(group: 'com.google.gwt', name: 'gwt-user', version: '2.7.0')
    testCompile(group: 'junit', name: 'junit', version: '4.12')
}

artifacts {
    archives sourcesJar
    archives javadocJar
    archives jar
}

signing { sign configurations.archives }

def String getRepoUploadArchives() {
    getBuildModuleVersion().endsWith('SNAPSHOT') ? 'https://oss.sonatype.org/content/repositories/snapshots/' : 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
}

def String getUserNameUploadArchives() {
    project.findProperty('sonatype_username_ahome') ?: ''
}

def String getPassWordUploadArchives() {
    project.findProperty('sonatype_password_ahome') ?: ''
}

uploadArchives {
    repositories {
        mavenDeployer {
            beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
            repository(url: getRepoUploadArchives()) {
                authentication(userName: getUserNameUploadArchives(), password: getPassWordUploadArchives())
            }
            pom.project {
                name 'Lienzo-Core'
                packaging 'jar'
                description 'Ahome Lienzo Core - GWT library for high-speed Structued Graphics based on the Canvas element.'
                url 'https://github.com/ahome-it/lienzo-core'
                scm {
                    url 'scm:git@github.com:ahome-it/lienzo-core.git'
                    connection 'scm:git@github.com:ahome-it/lienzo-core.git'
                    developerConnection 'scm:git@github.com:ahome-it/lienzo-core.git'
                }
                licenses {
                    license {
                        name 'The Apache Software License, Version 2.0'
                        url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                        distribution 'repo'
                    }
                }
                developers {
                    developer {
                        id 'sprocketnyc'
                        name 'Dean S. Jones'
                        email 'deansjones@gmail.com'
                        url 'https://www.lienzo-core.com'
                    }
                }
            }
        }
    }
}

def Map<String, List<String>> getGroovydocLinks() {
    def lmap = [:]
    def data = project.file('groovydoc/GROOVYDOC_LINK_LISTS.txt')
    if (data.exists()) {
        data.eachLine { line ->
            def vals = ((CharSequence) line).tokenize(',')
            lmap[vals.head()] = vals.tail()
        }
    }
    lmap
}

task buildGroovydocLinks {
    doLast {
        def site = [:]
        def data = project.file('groovydoc/GROOVYDOC_LINK_SITES.txt')
        if (data.exists()) {
            data.eachLine { line ->
                site[line] = ((CharSequence) new URL("${line}/package-list").text).tokenize('\n')
            }
        }
        def make = project.file('groovydoc/GROOVYDOC_LINK_LISTS.txt')
        if (make.exists()) {
            make.delete()
        }
        make.createNewFile()
        def save = make.newPrintWriter()
        site.each { link, list ->
            def show = "${link}"
            list.each { line -> show = "${show},${line}" }
            save.println("${show}")
        }
        save.flush()
        save.close()
    }
}