import java.util.regex.Matcher
import java.util.regex.Pattern

buildscript {
    repositories {
        google()
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath "gradle.plugin.com.gladed.gradle.androidgitversion:gradle-android-git-version:0.4.5"
    }
}

allprojects {
    repositories {
        google() // and here
        jcenter()
    }
}

apply plugin: "com.android.application"
apply plugin: "com.gladed.androidgitversion"

def getCurrentFlavor() {
    Gradle gradle = getGradle()

    if (gradle.getStartParameter().getTaskRequests().args.size() == 0)
        return ""
    String  tskReqStr = gradle.getStartParameter().getTaskRequests().args[0][0]
    Pattern pattern

    pattern = Pattern.compile("(\\w*)(Release|Debug)")

    Matcher matcher = pattern.matcher( tskReqStr )

    if( matcher.find() )
        return matcher.group(2).toLowerCase()
    else
    {
        println "NO MATCH FOUND"
        return ""
    }
}

def flavor = getCurrentFlavor()
def flavor_cap = getCurrentFlavor().capitalize()

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def sdkDir = properties.getProperty("sdk.dir")
def classpath = "build/intermediates/javac/${flavor}/compile${flavor_cap}JavaWithJavac/classes;${sdkDir}/platforms/android-26/android.jar"
def activity = "com.omixlab.panopainter.MainActivity"
def outpath = "src/main/cpp"

def ver_branch = "git rev-parse --abbrev-ref HEAD".execute().text.trim()
def ver_hash = "git log --pretty=format:%h -n 1".execute().text.trim()
def ver_count = Integer.parseInt("git rev-list --count HEAD".execute().text.trim())
def ver_tag = "git describe --tags --abbrev=0".execute().text.trim()

println classpath

android {
    compileSdkVersion 26
    android.buildToolsVersion "28.0.3"

    defaultConfig {
        applicationId = 'com.omixlab.panopainter'
        minSdkVersion   19
        targetSdkVersion 26
        versionCode ver_count
        versionName "${ver_tag}.${ver_count}"
        // This block is different from the one you use to link Gradle
        // to your CMake or ndk-build script.
        externalNativeBuild {
            // For ndk-build, instead use the ndkBuild block
            cmake {
                // Passes optional arguments to CMake.
                //arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_TOOLCHAIN=clang"
                // Sets optional flags for the C compiler.
                //cFlags "-D_EXAMPLE_C_FLAG1", "-D_EXAMPLE_C_FLAG2"
                // Sets a flag to enable format macro constants for the C++ compiler.
                //cppFlags "-D__STDC_FORMAT_MACROS"
                arguments   "-DANDROID_TOOLCHAIN=clang",
                            //"-DANDROID_PLATFORM=android-19",
                            "-DANDROID_STL=c++_shared",
                            "-DCMAKE_BUILD_TYPE=${flavor_cap}",
                            "-DANDROID_ARM_NEON=TRUE"
            }
        }
        ndk {
          // Specifies the ABI configurations of your native
          // libraries Gradle should build and package with your APK.
          // abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a'
          abiFilters 'armeabi-v7a', 'arm64-v8a'
        }
    }

    // productFlavors {
    //     main {
    //         externalNativeBuild {
    //             cmake {
    //                 targets "native-lib-demo"
    //             }
    //         }
    //     }
    // }

    signingConfigs {
        release {
            storeFile file("ppkey.jks")
            storePassword "om4r@Pano#Painter_2018"
            keyAlias "PanoPainter"
            keyPassword "om4r@Pano#Painter_2018"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFile getDefaultProguardFile('proguard-android.txt')
            signingConfig signingConfigs.release
        }
    }

      // Encapsulates your external native build configurations.
    externalNativeBuild {
        // Encapsulates your CMake build configurations.
        cmake {
          // Provides a relative path to your CMake build script.
          path "CMakeLists.txt"
        }
    }
}

task copyFiles(type: Copy) {
    from '../data/'
    into 'src/main/assets/data'
}
preBuild.dependsOn(copyFiles)

task generateVersioning(type: Exec) {
    workingDir "$projectDir/../"
    commandLine 'python', 'scripts/pre-build.py', flavor
}
copyFiles.dependsOn(generateVersioning)

task generateJavaH(type: Exec) {
    ignoreExitValue true
    workingDir "$projectDir"
    commandLine 'javah', "-jni", "-force", "-cp", "$classpath", "-d", "$outpath", "$activity"
}
//generateVersioning.dependsOn(generateJavaH)

tasks.whenTaskAdded { task ->
    if (task.name.contains('externalNativeBuild')) {
        // This dependecy *is* set. This can be seen by using task copyLibs(type: Copy, dependsOn: 'bundleDebug')
        // together with this and get a circular dependency.
        task.dependsOn generateJavaH
    }
}

repositories {
    google()
}