import groovy.xml.MarkupBuilder

apply plugin: 'com.github.ben-manes.versions'

//https://ed-george.github.io/articles/15-07-2020/gradle-sorting-reporting

def gitSha() {
    return 'git rev-parse --short HEAD'.execute([], rootDir).text.trim()
}

dependencyUpdates {
    outputFormatter = { result ->
        def updatable = result.outdated.dependencies
        if (!updatable.isEmpty()) {
            def filepath = "app/build/dependencyUpdates/${project.name}-dependencies-result.html"
            def file = new File(filepath)
            if (!file.exists()) {
                // Make the subdirectories
                file.getParentFile().mkdirs()
            }
            def fileWriter = new FileWriter(file)
            def html = new MarkupBuilder(fileWriter)

            html.html {
                head {
                    style("table{width:100%}table,td,th{border:1px solid #4b636e;border-collapse:collapse}td,th{padding:15px;text-align:left}table tr:nth-child(even){background-color:#f5f5f6}table tr:nth-child(odd){background-color:#e1e2e1}table th{background-color:#4b636e;color:#ffffff}")
                }
                body {
                    h3("Module: $project.name")
                    h3("Git commit: ${gitSha()}")
                    h4("Last updated: ${LocalDateTime.now()}")
                    table {
                        tr {
                            th("Group")
                            th("Module")
                            th("Current version")
                            th("Latest version")
                        }
                        updatable.each { dependency ->
                            tr {
                                td(dependency.group)
                                td(dependency.name)
                                td(dependency.version)
                                td(dependency.available.release ?: dependency.available.milestone)
                            }
                        }
                    }
                }
            }
            println "[DEPENDENCY REPORTER] Generated file: $filepath"
        }
    }
}