import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

task verifyPandoc {
    doLast{
        def result = exec{
            def command = "pandoc"
            ignoreExitValue = true
            if(DefaultNativePlatform.currentOperatingSystem.isWindows()){
                executable = "cmd"
                args "/C", command
            } else {
                executable = "bash"
                args "-c", command
            }
        }
        if(result.getExitValue()!=0){
            throw new Exception ("""
            >> Task requires 'pandoc'.
            >> Please ensure your system has 'pandoc' installed https://pandoc.org/installing.html
            """)
        }
    }
}

//tag::convertToDocx[]
task convertToDocx (
        group: 'docToolchain',
        description: 'converts file to .docx via pandoc. Needs pandoc installed.',
        type: Exec
) {
    // All files with option `docx` in config.groovy is converted to docbook and then to docx.
    def sourceFilesDocx = sourceFiles.findAll { 'docx' in it.formats }
    def explicitSourceFilesCount = sourceFilesDocx.size()
    if(explicitSourceFilesCount==0){
        sourceFilesDocx = sourceFiles.findAll { 'docbook' in it.formats }
    }
    sourceFilesDocx.each {
        def sourceFile = it.file.replace('.adoc', '.xml')
        def targetFile = sourceFile.replace('.xml', '.docx')

        new File("$targetDir/docx/$targetFile")
            .getParentFile()
            .getAbsoluteFile().mkdirs()

        workingDir "$targetDir/docbook"
        executable = "pandoc"

        def pandocOptions = config.pandocOptions ?: []

        if(referenceDocFile?.trim()) {
            args = ["-r","docbook",
                    "-t","docx",
                    "-o","../docx/$targetFile",
                    *pandocOptions,
                    "--reference-doc=${docDir}/${referenceDocFile}",
                    sourceFile]
        } else {
            args = ["-r","docbook",
                    "-t","docx",
                    "-o","./../docx/$targetFile",
                    *pandocOptions,
                    sourceFile]
        }
    }
    doFirst {
        if(sourceFilesDocx.size()==0){
            throw new Exception ("""
            >> No source files defined for type 'docx'.
            >> Please specify at least one inputFile in your docToolchainConfig.groovy
            """)
        }
        if(explicitSourceFilesCount==0) {
            logger.warn('WARNING: No source files defined for type "docx". Converting with best effort')
        }
    }
}
//end::convertToDocx[]

//tag::convertToEpub[]
task convertToEpub (
        group: 'docToolchain',
        description: 'converts file to .epub via pandoc. Needs pandoc installed.',
        type: Exec
) {
    // All files with option `epub` in config.groovy is converted to docbook and then to epub.
    def sourceFilesEpub = sourceFiles.findAll { 'epub' in it.formats }
    def explicitSourceFilesCount = sourceFilesEpub.size()
    if(explicitSourceFilesCount==0){
        sourceFilesEpub = sourceFiles.findAll { 'docbook' in it.formats }
    }
    sourceFilesEpub.each {
        def sourceFile = it.file.replace('.adoc', '.xml')
        def targetFile = sourceFile.replace('.xml', '.epub')

        new File("$targetDir/epub/$targetFile")
            .getParentFile()
            .getAbsoluteFile().mkdirs()

        workingDir "$targetDir/docbook"
        executable = "pandoc"
        args = ['-r','docbook',
                '-t','epub',
                '-o',"../epub/$targetFile",
                sourceFile]
    }
    doFirst {
        if(sourceFilesEpub.size()==0){
            throw new Exception ("""
            >> No source files defined for type 'epub'.
            >> Please specify at least one inputFile in your docToolchainConfig.groovy
            """)
        }
        if(explicitSourceFilesCount==0) {
            logger.warn('WARNING: No source files defined for type "epub". Converting with best effort')
        }
    }
}
//end::convertToEpub[]
project.afterEvaluate {
    project.tasks.convertToDocx.dependsOn verifyPandoc
    project.tasks.convertToEpub.dependsOn verifyPandoc
    project.tasks.convertToDocx.dependsOn generateDocbook
    project.tasks.convertToEpub.dependsOn generateDocbook
}

//tag::createReferenceDoc[]
task createReferenceDoc (
        group: 'docToolchain helper',
        description: 'creates a docx file to be used as a format style reference in task convertToDocx. Needs pandoc installed.',
        type: Exec
) {
    workingDir "$docDir"
    executable = "pandoc"
    args = ["-o", "${docDir}/${referenceDocFile}",
            "--print-default-data-file",
            "reference.docx"]

    doFirst {
        if(!(referenceDocFile?.trim())) {
            throw new GradleException("Option `referenceDocFile` is not defined in config.groovy or has an empty value.")
        }
    }
}
//end::createReferenceDoc[]

