import java.nio.file.Files
import java.nio.file.Paths

//tag::downloadTemplate[]
task downloadTemplate(
    description: 'Download a specified template and install it',
    group: 'docToolchain helper'
) {
    doFirst {
    }
    doLast {
        def color = { color, text ->
            def colors = [black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37]
            return new String((char) 27) + "[${colors[color]}m${text}" + new String((char) 27) + "[0m"
        }
        def lang, help, antora
        def templates = [
            arc42:"https://github.com/arc42/arc42-template/raw/master/dist/arc42-template-${->lang}-${->help}-asciidoc.zip",
            req42:"https://github.com/Hruschka/req42-framework/raw/main/dist/req42-framework-${->lang}-${->help}-asciidoc.zip"
        ]
        def languages = [
                arc42: ['CZ', 'DE', 'EN', 'ES', 'FR', 'IT', 'NL', 'UA'],
                req42:['EN', 'DE']
        ]
        for (int i=1; i<20; i++) {
            def template = System.getenv('DTC_TEMPLATE' + i) ?: ""
            if (template) {
                def name = template.replaceAll("^.*/","").replaceAll(/.zip$/,"")
                templates << [(name):template]
            }
        }
        def template = 'arc42'
        if (templates.size()>1) {
            def prompt = ""
            templates.eachWithIndex { templateName, url, i ->
                prompt += "\n ${color 'green', "${i+1}) $templateName"}"
            }
            ant.input(message: "${color 'green', "Which template do you want to install?"}$prompt\n", validargs: (1..templates.size()).join(","), addproperty: 'template')
            template = templates.keySet()[(ant.template as Integer)-1]
        }
        println "${color 'green', 'Install '+template+' documentation template.'}"
        if (template in ['arc42', 'req42']) {
            if (template=='arc42') {
                println "For more information about arc42 see https://arc42.org"
            } else {
                println "For more information about req42 see https://req42.de/en"
            }
            ant.input(message: "${color 'green', 'Which language do you want to install?'}", validargs: languages[template].join(','), addproperty: 'lang')
            ant.input(message: "${color 'green', 'Do you want the template with or without help?'}", validargs: 'withhelp,plain', addproperty: 'help')
            ant.input(message: "${color 'green', 'Do you want the template to be setup for Antora? (experimental)'}", validargs: 'n,y', addproperty: 'antora')
            lang = ant.lang
            help = ant.help
            antora = ant.antora.toBoolean()
        }
        def outputDir = new File(docDir, Paths.get(inputPath, template).toString())
        outputDir.mkdirs()
        download.run {
            src templates[template]
            dest new File(outputDir, 'template.zip')
            overwrite true
        }
        copy {
            from zipTree(new File(outputDir, 'template.zip'))
            into outputDir
        }
        delete {
            delete new File(outputDir, 'template.zip')
        }
        println "${template} template unpacked into ${outputDir}"

        def configFile = new File(docDir, mainConfigFile)

        if(antora && template in ['arc42', 'req42']){
            println "start to bootstrap Antora, this integration considered experimental"

            new File(outputDir, 'modules/ROOT/pages').mkdirs()
            new File(outputDir, 'modules/ROOT/assets/images').mkdirs()
            def examplesDirPath = Paths.get(outputDir.absolutePath, "/modules/ROOT/examples")
            examplesDirPath.toFile().mkdirs()

            // Here we create a symbolic link to task output folders that should be includable
            // currently works with `collectIncludes`
            Files.createSymbolicLink(
                Paths.get(examplesDirPath.toString(), "_includes"),
                Paths.get(targetDir as String, "_includes")
            )

            def nav = new File(outputDir, 'modules/ROOT/nav.adoc')
            nav.createNewFile()
            def navContent = [:]

            copy {
                from (new File(outputDir, 'images/.'))
                into new File(outputDir, 'modules/ROOT/assets/images/.')
            }
            delete new File(outputDir, 'images/.')

            copy {
                from (new File(outputDir, 'src/.'))
                into new File(outputDir, 'modules/ROOT/pages/.')
            }
            delete new File(outputDir, 'src/.')

            new File(outputDir, 'modules/ROOT/pages').eachFileRecurse { file->
                if (file.name.endsWith('.adoc') && file.name ==~ /[0-9]+_.*/) {
                    def text = file.getText('utf-8')
                    def title = ""
                    text.eachLine { line ->
                        if (title=="" && line.startsWith('=')) {
                            title = line.split("[ \t]+",2)[1]
                        }
                    }
                    text = text.replaceAll(/ifndef::imagesdir\[:imagesdir: \.\.\/images]/,
                        "")
                    text = """\
:jbake-title: $title
:jbake-type: page_toc
:jbake-status: published
:jbake-menu: $template
:jbake-order: ${file.name.split("_")[0] as Integer}
:filename: ${file.canonicalPath-outputDir.canonicalPath}
ifndef::imagesdir[:imagesdir: ../assets/images]

ifndef::optimize-content[]
:toc:
endif::optimize-content[]
"""+text
                    file.write(text,'utf-8')
                    def navIndex = file.name.split("_")[0]
                    navContent.put(navIndex as Integer, '* xref:'+file.name+'['+navIndex+'. '+title+']\n')
                }
            }
            def sortedNav = navContent.keySet().sort().collect { key ->
                navContent[key]}.join('\n');
            nav.write(sortedNav,'utf-8')

            new File(outputDir, 'modules/ROOT/pages/.asciidoctorconfig.adoc').text = ':imagesdir: ../assets/images'
            def templateConfig = new File(outputDir, 'modules/ROOT/pages/config.adoc')
            templateConfig.text = templateConfig.text.replaceAll(':imagesdir: ./images', ':imagesdir: ../assets/images')

            def templateFile = new File(outputDir, template == "arc42" ? "${template}-template.adoc" : "${template}-framework.adoc")
            def mainFile = new File(outputDir, "modules/ROOT/pages/index.adoc")
            copy {
                from (templateFile)
                into new File(outputDir, 'modules/ROOT/pages/.')
            }
            delete templateFile
            new File(outputDir, "modules/ROOT/pages/${templateFile.name}")
                .renameTo(mainFile)

            def mainFileTxt = mainFile.text.replaceAll('src/', '')

           mainFileTxt = mainFileTxt.replaceAll(/(?m)^= image:$template-logo\.png.*/, """\
ifndef::optimize-content[]
= image:$template-logo.png[$template] Template
endif::optimize-content[]

ifdef::optimize-content[]
image:arc42-logo.png[arc42]
endif::optimize-content[]
""")
            mainFileTxt = mainFileTxt.replaceAll(/include::about-${template}.adoc\[]/, """\
include::about-${template}.adoc[]

ifndef::optimize-content[]
""") + "\nendif::optimize-content[]"
            mainFile.write(mainFileTxt, 'utf-8')

            configFile.write(
                configFile.text
                    .replaceAll('//useAntoraIntegration = false', 'useAntoraIntegration = true')
                    .replaceAll('[, \\t\\r\\n]+/[*]{2} inputFiles [*]{2}/',
                        ",\n\t[file: '${template}/modules/ROOT/pages/index.adoc', formats: ['html','pdf']],\n\t/** inputFiles **/")
                    .replaceAll('/[*]{2} imageDirs [*]{2}/',
                        "'${template}/modules/ROOT/assets/images/.',\n\t/** imageDirs **/")
                    .replaceAll('[, \\t\\r\\n]+/[*]{2} imageDirs [*]{2}/',
                        ",\n\t'${template}/modules/ROOT/assets/images/.',\n\t/** imageDirs **/")
                    .replaceAll("\\[,", "["),
                'utf-8'
            )

            new File(outputDir, 'antora.yml').text = """\
name: ${template}-template
title: ${template} Template
version: latest
start_page: index.adoc
nav:
  - modules/ROOT/nav.adoc
asciidoc:
  attributes:
    optimize-content: true
"""

            println "finished to bootstrap antora"
        }

        //re-organize content
        //move images folder
        else {
            new File(outputDir, '../images/.').mkdirs()
            copy {
                from(new File(outputDir, 'images/.'))
                into new File(outputDir, '../images/.')
            }
            delete new File(outputDir, 'images/.')
            new File(outputDir, 'src').renameTo(new File(outputDir, 'chapters'))
            //add jbake header
            new File(outputDir, 'chapters').eachFileRecurse { file ->
                if (file.name.endsWith('.adoc') && file.name ==~ /[0-9]+_.*/) {
                    def text = file.getText('utf-8')
                    def title = ""
                    text.eachLine { line ->
                        if (title == "" && line.startsWith('=')) {
                            title = line.split("[ \t]+", 2)[1]
                        }
                    }
                    text = text.replaceAll(/ifndef::imagesdir\[:imagesdir: \.\.\/images]/,
                        "")
                    text = """\
:jbake-title: $title
:jbake-type: page_toc
:jbake-status: published
:jbake-menu: ${template}
:jbake-order: ${file.name.split("_")[0] as Integer}
:filename: ${file.canonicalPath - outputDir.canonicalPath}
ifndef::imagesdir[:imagesdir: ../../images]

:toc:

""" + text
                    file.write(text, 'utf-8')
                }
            }
            new File(outputDir, template == "arc42" ? "${template}-template.adoc" : "${template}-framework.adoc")
                .renameTo(new File(outputDir, "${template}.adoc"))
            def configAdoc = new File(outputDir, 'chapters/config.adoc')
            configAdoc.write(configAdoc.text.replaceAll("[.]/images", "../images"), 'utf-8')
            def mainDoc = new File(outputDir, "${template}.adoc")
            mainDoc.write(":imagesdir: ../images\n:jbake-menu: -\n" + mainDoc.text.replaceAll('src/', 'chapters/'), 'utf-8')
            //write asciidoctorconfig for editor preview
            new File(outputDir, '/chapters/.asciidoctorconfig.adoc').write(':imagesdir: ../../images\n\n', 'utf-8')
            new File(outputDir, '/.asciidoctorconfig.adoc').write(':imagesdir: ../images\n\n', 'utf-8')
            //add arc42.doc to config
            configFile.write(
                configFile.text
                    .replaceAll('[, \\t\\r\\n]+/[*]{2} inputFiles [*]{2}/',
                        ",\n\t[file: '${template}/${template}.adoc', formats: ['html','pdf']],\n\t/** inputFiles **/")
                    .replaceAll('/[*]{2} imageDirs [*]{2}/',
                        "'images/.',\n\t/** imageDirs **/")
                    .replaceAll('[, \\t\\r\\n]+/[*]{2} imageDirs [*]{2}/',
                        ",\n\t'images/.',\n\t/** imageDirs **/")
                    .replaceAll("\\[,", "["),
                'utf-8'
            )
        }
        println "added template to ${mainConfigFile}"
        println "use 'generateHTML', 'generatePDF' or  'generateSite' to convert the template"

    }
}
//end::downloadTemplate[]
