// Try to get a git commit id for javadoc
def getCommitHash() {
  if(!new File(".git").exists()) return ""
  // requires git installed
  try {
    def best = 'git rev-parse HEAD'.execute().text
    if(best != null && best.length > 5) return best
  } catch (Exception e) {}
  // No longer works reliably, because of packed references.
  try {
    def head = new File(".git", "HEAD").text.split(":")
    if (head.length == 1) return head[0].trim().take(12)
    return new File(".git", head[1].trim()).text.take(12)
  } catch (Exception e) {}
  return ""
}

// UMLgraph requires graphviz installed. Windows and OSX users, please provide a patch
def useuml = file('/usr/bin/dot').exists()

subprojects {
  if (useuml) {
    configurations { umlDoclet }
    dependencies { umlDoclet group: 'nl.talsmasoftware', name: 'umldoclet', version: '2.0.19' }
  }

  // Javadoc options
  javadoc {
    options {
      encoding = 'UTF-8'
      docEncoding = 'UTF-8'
      stylesheetFile = "$rootDir/elki/src/main/javadoc/stylesheet.css" as File
      noTree = false
      noNavBar = false
      noIndex = false
      noHelp = true
      splitIndex = true
      author = true
      use = true
      memberLevel = JavadocMemberLevel.PRIVATE
      noDeprecated = false
      noDeprecatedList = false
      docFilesSubDirs = true
      docTitle = 'ELKI'
      windowTitle = 'ELKI: Environment for DeveLoping KDD-Applications Supported by Index-Structures'
      if (new File("src/main/javadoc/overview.html").exists()) overview = "src/main/javadoc/overview.html"
      group('Algorithms', ['elki.algorithm*'])
      group('Databases and Index Structures', ['elki.database*', 'elki.index*', 'elki.datasource*', 'elki.persistent*'])
      group('Datatypes and Distance Functions', ['elki.data', 'elki.data.*', 'elki.distance*'])
      group('Evaluation', ['elki.evalu*'])
      group('GUI and Visualization', ['elki.gui*', 'elki.vis*'])
      group('Utilities and Miscellaneous', ['elki', 'elki.*'])
      group('Tutorial Code and Examples', ['tutorial', 'tutorial.*'])
      header = """<img src="{@docRoot}/figures/elki-logo-200.png" width="200"><script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>"""
      footer = """ELKI version $project.version"""
      if (isSnapshot) {
        def commit = getCommitHash()
        if (commit) footer += """ rev. $commit"""
        footer += """ built at $buildTime"""
      }
      bottom = """Copyright &copy; $year <a href="https://elki-project.github.io/">ELKI Development Team</a>. <a href="https://elki-project.github.io/license">License information.</a><!-- so we get to know what people search for: --><script>if(window.location.hostname=="elki-project.github.io"||window.location.hostname=="jitpack.io"||window.location.hostname=="javadoc.io"){(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create","UA-87792924-1","auto");ga("send","pageview");}</script>"""
      // We have cross-package references, and we allow missing javadoc in private classes.
      addBooleanOption('Xdoclint:all,-reference', true)
      // Java 8 was very fragile with respect to HTML
      if(JavaVersion.current().isJava8()) addBooleanOption('Xdoclint:none', true)
      // Add --allow-script-in-comments if available (some 1.8 versions only)
      if(JavaVersion.current().isJava8Compatible()) addBooleanOption('-allow-script-in-comments', true)
      if(JavaVersion.current().isJava9()) addBooleanOption('html4', true)
      if(JavaVersion.current().isJava11()) addBooleanOption('-no-module-directories', true)
      // UmlDoclet is optional - needs graphviz installed
      if (useuml) {
        docletpath = configurations.umlDoclet.files.asType(List)
        doclet = "nl.talsmasoftware.umldoclet.UMLDoclet"
        addStringOption "umlCustomDirective", "remove .*\\.(Instance|Par|Parameterizer|Factory)\$"
        addBooleanOption "createPumlFiles", true
      }
      tags("hidden:X", "opt:X", "has:X", "navhas:X", "assoc:X", "navassoc:X", "composed:X", "navcomposed:X", "stereotype:X", "depend:X")
    }
    inputs.property("options.footer","") // Ignore: depends on build time.
  }
  // Resources to copy to every javadoc
  task copyDocResources(type: Copy) {
    from("$rootDir/elki/src/main/javadoc") {
      include "**/stylesheet.css"
      include "**/elki-logo-200.png"
    }
    from("$projectDir/src/main/javadoc") {
      exclude "overview.html"
    }
    inputs.files fileTree("$rootDir/elki/src/main/javadoc")
    duplicatesStrategy DuplicatesStrategy.INCLUDE
    into "$project.buildDir/docs/javadoc"
  }
  javadoc.finalizedBy copyDocResources
  javadocJar.dependsOn copyDocResources
  // Additional documentation: parameters
  task documentParameters(type: JavaExec, dependsOn: classes) {
    description "Generate parameter documentation"
    group = "Documentation"
    classpath = sourceSets.test.runtimeClasspath
    inputs.files classpath
    outputs.file "$project.buildDir/docs/javadoc/parameters-byclass.html"
    mainClass = 'elki.application.internal.DocumentParameters'
    args "$project.buildDir/docs/javadoc/parameters-byclass.html"
    args "$project.buildDir/docs/javadoc/parameters-byopt.html"
  }
  // To use, add javadoc.dependsOn documentParameters
  // Additional documentation: references
  task documentReferences(type: JavaExec, dependsOn: classes) {
    description "Generate references list"
    group = "Documentation"
    classpath = sourceSets.test.runtimeClasspath
    inputs.files classpath
    outputs.file "$project.buildDir/docs/javadoc/references.html"
    mainClass = 'elki.application.internal.DocumentReferences'
    args "$project.buildDir/docs/javadoc/references.html"
    args "$project.buildDir/docs/references.md"
  }
  // To use, add javadoc.dependsOn documentReferences
}
