import groovy.io.FileType
import org.apache.tools.ant.taskdefs.condition.Os

String winapp_input_dir = 'BIN'

def defineWinDistTasks =  { javaRuntime, distName -> 

    def appImageDir = file("build/winapp/${javaRuntime}")
    def winapp_deleteAppImage = tasks.create("winapp_deleteAppImage_${javaRuntime}", Delete) { 
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }
        delete "${appImageDir}" 
    }

    def winapp_input = tasks.create("winapp_input_${javaRuntime}", Copy) {
        onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }
        
        from(winapp_input_dir) {
            include '*.jar'
        }
        
        into "${appImageDir}"

        doLast {
            mkdir "${appImageDir}/input"
        }

        dependsOn winapp_deleteAppImage

        for (p in subprojects) {
            dependsOn p.tasks.getByPath("build")
        }

    }


    def jpackage = 'jpackage'

    def jpackage_winapp = tasks.create ("jpackage_winapp_${javaRuntime}", Exec) {
        onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

        commandLine jpackage,
                '--name' , 'freeplane',
        '--type', 'app-image',
        '--icon', 'freeplane_framework/launch4j/Freeplane_app.ico',
        '--app-version', majorVersion,
        '--java-options', "-XX:-IgnoreUnrecognizedVMOptions",
        '--java-options', "-XX:MaxRAM=20g",
        '--java-options', "-XX:MaxRAMPercentage=15.0",
        '--java-options', '-Djava.security.manager=allow',
        '--java-options', '-Dorg.freeplane.userfpdir=%APPDATA%\\Freeplane',
        '--java-options', '--add-exports', 
        '--java-options', 'java.desktop/sun.awt=ALL-UNNAMED',
        '--java-options', '--add-exports', 
        '--java-options', 'java.desktop/sun.awt.shell=ALL-UNNAMED',
        '--java-options', '--add-exports', 
        '--java-options', 'java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED',
        '--java-options', '--add-exports', 
        '--java-options', 'java.desktop/sun.swing=ALL-UNNAMED',
        '--java-options', '--add-opens', 
        '--java-options', 'java.desktop/javax.swing.text.html=ALL-UNNAMED',
        '--input', "build/winapp/${javaRuntime}/input",
        '--main-class', 'org.freeplane.launcher.Launcher',
        '--main-jar', '../freeplanelauncher.jar',
        '--add-launcher', 'freeplaneConsole=freeplane_framework/launch4j/freeplaneConsole.properties',
        '--runtime-image', "java-runtime-${javaRuntime}",
        '--copyright', "Freeplane ${distVersion}",
        '--dest', "${appImageDir}"
        dependsOn winapp_deleteAppImage, winapp_input

        for (p in subprojects) {
            dependsOn p.tasks.getByPath("build")
        }
    }
    
    def winapp_makeapp = tasks.create("winapp_makeapp_${javaRuntime}", Copy) {
        onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }
        dependsOn jpackage_winapp
        
        from(winapp_input_dir) {
            include '*/**'
            exclude '/*.exe'
            exclude '/*.l4j.ini'
        }
        
        into "${appImageDir}/Freeplane/"
    }


    def windowsInstaller = tasks.create("windowsInstaller_${javaRuntime}", Exec) {
        onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

        ignoreExitValue = true
        workingDir = rootDir.path + '/freeplane_framework/windows-installer'

        commandLine 'cmd.exe', '/c', "ISCC.exe /DAppImage=${appImageDir} /Q Freeplane.iss "
        doLast {
            new File(workingDir, 'Freeplane-Setup.exe').renameTo(new File(globalDist, "Freeplane-Setup${distName}-${distVersion}.exe"))
        }

        dependsOn winapp_makeapp
    }
    
    dist {
        dependsOn windowsInstaller
    }

}

if ( Os.isFamily(Os.FAMILY_WINDOWS)) {
    defineWinDistTasks('jbr', '')
    defineWinDistTasks('zulu', '-touchscreen')
}


def portableInstallerDir = new File(globalDist, 'FreeplanePortable').path

task copyWindowsPortableInstallerBasicFiles(type: Copy) {
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

    // copy windows-portable files
    from(rootDir.path + '/freeplane_framework/windows-portable') {
         include('**')
    }
    into(portableInstallerDir)
}
task copyWindowsPortableInstallerLicense(type: Copy) {
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

    // copy license
    from(rootDir.path + '/freeplane/resources/') {
         include('license.txt')
         rename('license.txt', 'EULA.txt')
    }
    into(portableInstallerDir + '/Other/Source/')
}
task copyWindowsPortableInstallerIcon(type: Copy) {
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

    // copy icon
    from(rootDir.path + '/freeplane_framework/launch4j') {
        include('Freeplane_app.ico')
        rename('Freeplane_app.ico', 'appicon.ico')
    }
    into(portableInstallerDir + '/App/AppInfo/')
}


task copyWindowsPortableInstallerFiles(type: Copy) {
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

    // copy INI I
    from(rootDir.path + '/freeplane_framework/portableApps') {
        include('portable.ini')
        rename('portable.ini', 'freeplane.l4j.ini')
    }

    // copy INI II
    from(rootDir.path + '/freeplane_framework/portableApps') {
        include('portable.ini')
        rename('portable.ini', 'freeplaneConsole.l4j.ini')
    }

    // copy all other files
    from (globalBin) {
        exclude('*.bat', '*.ini', '*.sh')
    }
    into(portableInstallerDir + '/App/Freeplane/')

    for (p in subprojects) {
        dependsOn p.tasks.getByPath("build")
    }
    dependsOn copyWindowsPortableInstallerBasicFiles
    dependsOn copyWindowsPortableInstallerLicense
    dependsOn copyWindowsPortableInstallerIcon
}


task windowsPortableInstaller(type: Exec) {
    onlyIf { Os.isFamily(Os.FAMILY_WINDOWS) }

    // continue the build when running windows but PortableApps.comInstaller.exe is not installed?
    ignoreExitValue = true
    workingDir = rootDir.path + '/freeplane_framework'

    commandLine 'cmd.exe', '/c', 'PortableApps.comInstaller.exe', portableInstallerDir

    dependsOn copyWindowsPortableInstallerFiles

    doLast {
         new File(portableInstallerDir).deleteDir() 
         new File(globalDist).eachFileMatch(FileType.FILES, ~/FreeplanePortable_.*\.paf\.exe/) {
			 f -> 
			 f.renameTo(new File(globalDist, "FreeplanePortable-${distVersion}.paf.exe"))
		 }
    }
}
