sourceSets.main{
    java.srcDirs = ['src/']
}

import arc.files.*

final def dexedJar = (project(':main').tasks.dex as Jar).archiveFile.get().asFile
final def distJar = (project(':main').tasks.deploy as Jar).archiveFile.get().asFile
final def regularJar = (project(':main').tasks.jar as Jar).archiveFile.get().asFile

final def usedClasspath =
    taskNames.contains('main:dex') ? dexedJar :
    taskNames.contains('main:deploy') ? distJar :
    dexedJar.exists() ? dexedJar :
    distJar.exists() ? distJar :
    regularJar

dependencies{
    if(
    !usedClasspath.exists() || toolRecompile ||
        taskNames.contains('main:deploy') || taskNames.contains('main:dex')
    ){
        implementation project(':main')
        if(taskNames.contains('tools:proc')) println 'Compiling :main project before processing assets...'
    }else{
        implementation files(usedClasspath)
    }

    implementation "com.github.Anuken.MindustryJitpack:core:$mindustryVersion"
    implementation "com.github.Anuken.Arc:arc-core:$arcVersion"
}

task rearchive{
    final def listStr = file(assetsDir).list()

    task archDexed(type: Jar){
        if(!dexedJar.exists() || taskNames.contains('main:dex')) ':main:dex'

        archiveFileName.set dexedJar.getName()
        from files(assetsDir){ exclude 'sprites/vanilla/**' }

        from(zipTree(dexedJar)){
            for(final def list : listStr) exclude "$list/**"
        }

        duplicatesStrategy = DuplicatesStrategy.EXCLUDE
        doLast{
            new Fi(dexedJar).writeBytes(new Fi(file(archiveFile.get())).readBytes())
        }
    }

    task archDist(type: Jar){
        if(!distJar.exists() || taskNames.contains('main:deploy')) ':main:deploy'

        archiveFileName.set distJar.getName()
        from files(assetsDir){ exclude 'sprites/vanilla/**' }

        from(zipTree(distJar)){
            for(final def list : listStr) exclude "$list/**"
        }

        duplicatesStrategy = DuplicatesStrategy.EXCLUDE
        doLast{
            new Fi(distJar).writeBytes(new Fi(file(archiveFile.get())).readBytes())
        }
    }

    def finalize = []
    if(distJar.exists() || taskNames.contains('main:deploy')) finalize += archDist
    if(dexedJar.exists() || taskNames.contains('main:dex')) finalize += archDexed

    finalizedBy finalize
}

task proc(dependsOn: [classes, configurations.runtimeClasspath]){
    if(toolRearchive){
        finalizedBy tasks.rearchive
        if(taskNames.contains('tools:proc')) println '.jar files will be re-archived after processing sprites.'
    }

    doLast{
        delete{ delete spritesDir }
        spritesDir.mkdirs()

        copy{
            from spritesRawDir
            into spritesDir
        }

        javaexec{
            workingDir = assetsDir
            main = 'unity.tools.Tools'
            classpath = sourceSets.main.runtimeClasspath
        }
    }
}
