import groovy.json.JsonSlurper
import org.gradle.internal.logging.text.StyledTextOutputFactory
import static org.gradle.internal.logging.text.StyledTextOutput.Style
import java.nio.file.Paths

apply plugin: 'com.android.library'
// AGP 9+ ships built-in Kotlin support; applying kotlin-android there fails
if (com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.split('\\.')[0] as int < 9) {
    apply plugin: 'kotlin-android'
}
apply plugin: 'kotlin-parcelize'

def loadPropertyFile = { path ->
    try {
        if(project.hasProperty("loadedProperties_${path}")) {
            logger.info "\t + gradle properties already loaded. SKIPPING"
        } else {
            logger.info "\t + trying to load gradle properties from \"$path\""

            Properties properties = new Properties()
            properties.load(new FileInputStream("$path"))
            properties.each { prop ->
                logger.info "\t + [$path] setting ${prop.key} = ${prop.value}"
                project.ext.set(prop.key, prop.value)
            }
            project.ext.set("loadedProperties_${path}", true)
            
            outLogger.withStyle(Style.SuccessHeader).println "\t + loaded gradle properties from \"$path\""
        }
    } catch(Exception ex) {
        logger.warn "\t + failed to load gradle properties from \"$path\". Error is: ${ex.getMessage()}"
    }
}

buildscript {
    def GRADLE_PROPERTIES_FILENAME = "gradle.properties"

    def getFile = { dir, filename ->
        File file = new File("$dir$File.separator$filename")
        file?.exists() ? file : null
    }

    def getPropertyFile = { dir ->
        return getFile(dir, GRADLE_PROPERTIES_FILENAME)
    }
    def getUserProperties = { dir ->
        def file = getPropertyFile(dir)
        if (!file) {
            return null
        }

        Properties properties = new Properties()
        properties.load(file.newInputStream())

        return properties
    }
    def loadPropertyFile = { path ->
        try {
            if(project.hasProperty("loadedProperties_${path}")) {
                logger.info "\t + gradle properties already loaded. SKIPPING"
            } else {
                logger.info "\t + trying to load gradle properties from \"$path\""

                Properties properties = new Properties()
                properties.load(new FileInputStream("$path"))
                properties.each { prop ->
                    logger.info "\t + [$path] setting ${prop.key} = ${prop.value}"
                    project.ext.set(prop.key, prop.value)
                }
                project.ext.set("loadedProperties_${path}", true)
                
                outLogger.withStyle(Style.SuccessHeader).println "\t + loaded gradle properties from \"$path\""
            }
        } catch(Exception ex) {
            logger.warn "\t + failed to load gradle properties from \"$path\". Error is: ${ex.getMessage()}"
        }
    }
    

    project.ext.getAppPath = { ->
        // def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json")
        // def nsConfig

        // if (nsConfigFile.exists()) {
        //     nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
        // }
        def relativePathToApp = "app"
        if (project.hasProperty("appPath")) {
            // when appPath is passed through -PappPath=/path/to/app
            // the path could be relative or absolute - either case will work
            relativePathToApp = appPath
        // } else if (nsConfig != null && nsConfig.appPath != null) {
        //     relativePathToApp = nsConfig.appPath
        }

        project.ext.appPath = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToApp).toAbsolutePath()

        return project.ext.appPath
    }
    project.ext.getBuildPath = { ->
        // def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json")
        // def nsConfig

        // if (nsConfigFile.exists()) {
        //     nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
        // }
        def relativeBuildToApp = "platforms"
        if (project.getProperty("appBuildPath")) {
            relativeBuildToApp = appBuildPath
        // } else if (nsConfig != null && nsConfig.buildPath != null) {
        //     relativeBuildToApp = nsConfig.buildPath
        }
        project.ext.relativeBuildPath = relativeBuildToApp
        project.ext.buildPath = Paths.get(USER_PROJECT_ROOT).resolve(relativeBuildToApp).toAbsolutePath()
        return project.ext.relativeBuildPath
    }
    project.ext.getAppResourcesPath = { ->
        // def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json")
        // def nsConfig

        // if (nsConfigFile.exists()) {
        //     nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
        // }
        def relativePathToAppResources
        def absolutePathToAppResources

        if (project.hasProperty("appResourcesPath")) {
            // when appResourcesPath is passed through -PappResourcesPath=/path/to/App_Resources
            // the path could be relative or absolute - either case will work
            relativePathToAppResources = appResourcesPath
            absolutePathToAppResources = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToAppResources).toAbsolutePath()
        // } else if (nsConfig != null && nsConfig.appResourcesPath != null) {
        //     relativePathToAppResources = nsConfig.appResourcesPath
        //     absolutePathToAppResources = Paths.get(USER_PROJECT_ROOT).resolve(relativePathToAppResources).toAbsolutePath()
        } else {
            absolutePathToAppResources = "${project.ext.getAppPath()}/App_Resources"
        }

        project.ext.appResourcesPath = absolutePathToAppResources

        return absolutePathToAppResources
    }

    project.ext.applyBeforePluginGradleConfiguration = { ->
        def appResourcesPath = project.ext.getAppResourcesPath()
        def pathToBeforePluginGradle = "$appResourcesPath/Android/before-plugins.gradle"
        def beforePluginGradle = file(pathToBeforePluginGradle)
        if (beforePluginGradle.exists()) {
            outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined configuration from ${beforePluginGradle}"
            apply from: pathToBeforePluginGradle
        }
    }


    def initialize = { ->
        // set up our logger
        project.ext.outLogger = services.get(StyledTextOutputFactory).create("colouredOutputLogger")
        outLogger.withStyle(Style.SuccessHeader).println "\t ~initialize"


        project.ext.USER_PROJECT_ROOT = "$rootDir/../.."
        if (project.hasProperty('projectRoot')) {
            project.ext.USER_PROJECT_ROOT = projectRoot
        }
        project.ext.PLATFORMS_ANDROID = project.ext.getBuildPath() + "/android"
        project.ext.PLUGIN_NAME = "{{pluginName}}"
        
        def userDir = "$USER_PROJECT_ROOT"
        rootProject.ext.userDefinedGradleProperties = getUserProperties("${project.ext.getAppResourcesPath()}/Android")

        loadPropertyFile("$USER_PROJECT_ROOT/${project.ext.PLATFORMS_ANDROID}/gradle.properties")
        loadPropertyFile("$USER_PROJECT_ROOT/${project.ext.PLATFORMS_ANDROID}/additional_gradle.properties")
        
        if (rootProject.hasProperty("userDefinedGradleProperties")) {
            rootProject.ext.userDefinedGradleProperties.each { entry ->
                def propertyName = entry.getKey()
                def propertyValue = entry.getValue()
                project.ext.set(propertyName, propertyValue)
            }
        }

        def getDepPlatformDir = { dep ->
            file("${project.ext.USER_PROJECT_ROOT}/${project.ext.PLATFORMS_ANDROID}/${dep.directory}/platforms/android")
        }

        // Set up styled logger
        project.ext.getDepPlatformDir = getDepPlatformDir
        project.ext.outLogger = services.get(StyledTextOutputFactory).create("colouredOutputLogger")


        // the build script will not work with previous versions of the CLI (3.1 or earlier)
        def dependenciesJson = file("${project.ext.USER_PROJECT_ROOT}/${project.ext.PLATFORMS_ANDROID}/dependencies.json")
        def appDependencies = new JsonSlurper().parseText(dependenciesJson.text)
        def pluginData = appDependencies.find { it.name == project.ext.PLUGIN_NAME }
        project.ext.nativescriptDependencies = appDependencies.findAll{pluginData.dependencies.contains(it.name)}.plus([pluginData])
    }

    initialize()
    project.ext.applyBeforePluginGradleConfiguration()

    def applyBuildScriptConfigurations = { ->
        def absolutePathToAppResources = project.ext.getAppResourcesPath()
        def pathToBuildScriptGradle = "$absolutePathToAppResources/Android/buildscript.gradle"
        def buildScriptGradle = file(pathToBuildScriptGradle)
        if (buildScriptGradle.exists()) {
            outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined buildscript from ${buildScriptGradle}"
            apply from: pathToBuildScriptGradle, to: buildscript
        }

        nativescriptDependencies.each { dep ->
            def pathToPluginBuildScriptGradle = "${getDepPlatformDir(dep)}/buildscript.gradle"
            def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle)
            if (pluginBuildScriptGradle.exists()) {
                outLogger.withStyle(Style.SuccessHeader).println "\t + applying user-defined buildscript from dependency ${pluginBuildScriptGradle}"
                apply from: pathToPluginBuildScriptGradle, to: buildscript
            }
            // def pathToPluginProjectBuildScriptGradle = "${getDepPlatformDir(dep)}/project-buildscript.gradle"
            // def pluginProjectBuildScriptGradle = file(pathToPluginProjectBuildScriptGradle)
            // if (pluginProjectBuildScriptGradle.exists()) {
            //     outLogger.withStyle(Style.SuccessHeader).println "\t + applying user-defined project-buildscript from dependency ${pluginProjectBuildScriptGradle}"
            //     apply from: pathToPluginProjectBuildScriptGradle, to: project
            // }
        }

        def pathToPluginBuildScriptGradle = "$rootDir/buildscript.gradle"
        def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle)
        if (pluginBuildScriptGradle.exists()) {
            outLogger.withStyle(Style.SuccessHeader).println "\t ~ applying user-defined buildscript from dependency ${pluginBuildScriptGradle}"
            apply from: pathToPluginBuildScriptGradle, to: buildscript
        }
    }

    applyBuildScriptConfigurations()

    def computeKotlinVersion = { -> project.hasProperty("kotlinVersion") ? kotlinVersion : "${ns_default_kotlin_version}" }
    def computeBuildToolsVersion = { -> project.hasProperty("androidBuildToolsVersion") ? androidBuildToolsVersion : "{{runtimeAndroidPluginVersion}}" }
    def kotlinVersion = computeKotlinVersion()
    def androidBuildToolsVersion = computeBuildToolsVersion()

    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$androidBuildToolsVersion"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
    }

}

def pluginDependencies

allprojects {
    repositories {
        // used for local *.AAR files
        pluginDependencies = nativescriptDependencies.collect {
            getDepPlatformDir(it)
        }

        // some plugins may have their android dependencies in a /libs subdirectory
        pluginDependencies.addAll(nativescriptDependencies.collect {
            "${getDepPlatformDir(it)}/libs"
        })
        mavenLocal()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        if (pluginDependencies.size() > 0) {
            flatDir {
                dirs pluginDependencies
            }
        }
    }
}


def computeCompileSdkVersion = { -> project.hasProperty("compileSdk") ? compileSdk as int : 35 }
def computeTargetSdkVersion = { -> project.hasProperty("targetSdk") ? targetSdk as int : 35 }
def computeBuildToolsVersion = { ->
    project.hasProperty("buildToolsVersion") ? buildToolsVersion : "35.0.1"
}

android {
    namespace "{{pluginNamespace}}"
    def applyPluginGradleConfigurations = { ->
        nativescriptDependencies.each { dep ->
            def includeGradlePath = "${getDepPlatformDir(dep)}/include.gradle"
            if (file(includeGradlePath).exists()) {
                outLogger.withStyle(Style.SuccessHeader).println "\t + applying plugin include.gradle from dependency ${includeGradlePath}"
                apply from: includeGradlePath
            }
        }
    }

    project.ext.applyBeforePluginGradleConfiguration()
    applyPluginGradleConfigurations()

    compileSdkVersion computeCompileSdkVersion()
    buildToolsVersion computeBuildToolsVersion()

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    if (project.hasProperty("ndkVersion")) {
        ndkVersion project.ndkVersion
    }

    defaultConfig {
        targetSdkVersion computeTargetSdkVersion()
        versionCode 1
        versionName "1.0"
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
}

task addDependenciesFromNativeScriptPlugins {
    nativescriptDependencies.each { dep ->
        def aarFiles = fileTree(dir: getDepPlatformDir(dep)).matching {
            include "**/*.aar"
            exclude "cpp/**"
            exclude project.hasProperty("aarIgnoreFilter") ? project.findProperty('aarIgnoreFilter').split(',').collect{it as String} : []
        }
        def currentDirname = file(project.buildscript.sourceFile).getParentFile().getName()
        aarFiles.each { aarFile ->
            def length = aarFile.name.length() - 4
            def fileName = aarFile.name[0..<length]
            if(fileName == currentDirname) {
                return
            }
            outLogger.withStyle(Style.SuccessHeader).println "\t + adding aar plugin dependency: " + aarFile.getAbsolutePath()
            project.dependencies.add("implementation", [name: fileName, ext: "aar"])
        }

        def jarFiles = fileTree(dir: getDepPlatformDir(dep)).matching {
            include "**/*.jar"
            exclude "cpp/**"
            exclude project.hasProperty("jarIgnoreFilter") ? project.findProperty('jarIgnoreFilter').split(',').collect{it as String} : []
        }
        jarFiles.each { jarFile ->
            def jarFileAbsolutePath = jarFile.getAbsolutePath()
            outLogger.withStyle(Style.SuccessHeader).println "\t + adding jar plugin dependency: $jarFileAbsolutePath"
            // pluginsJarLibraries.add(jarFile.getAbsolutePath())
        }

        project.dependencies.add("implementation", jarFiles)
    }
}

// This wont work with gradle 8 + should be the same as the code  just after
// afterEvaluate {
//     def generateBuildConfig =  project.hasProperty("generateBuildConfig") ? project.generateBuildConfig : false
//     def generateR =  project.hasProperty("generateR") ? project.generateR : false
//     generateReleaseBuildConfig.enabled = generateBuildConfig
//     generateDebugBuildConfig.enabled = generateBuildConfig
//     generateReleaseResValues.enabled = generateR
//     generateDebugResValues.enabled = generateR
// }
project.tasks.configureEach {
    if (name == 'bundleRelease') {
        def generateBuildConfig =  project.hasProperty("generateBuildConfig") ? project.generateBuildConfig : false
        def generateR =  project.hasProperty("generateR") ? project.generateR : false
        if (!generateBuildConfig) {
            it.exclude '**/BuildConfig.class'
        }
        if (!generateR) {
            it.exclude '**/R.class', '**/R$*.class'
        }
    }
}
