/*
 * Copyright(c) 2018 Bob Shen <ayst.shen@foxmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

apply plugin: 'com.android.application'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    defaultConfig {
        applicationId "com.ayst.stresstest"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode
        versionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }

        ndk {
            abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
        }
    }

    signingConfigs {
        release {
            File strFile = new File(rootProject.ext.keyStorePath)
            storeFile file(strFile)
            keyAlias rootProject.ext.keyStoreAlias
            keyPassword rootProject.ext.keyStoreKeyPassword
            storePassword rootProject.ext.keyStorePassword
        }
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release

            applicationVariants.all { variant ->
                variant.outputs.all {
                    def fileName = "AndroidStressTest_${variant.buildType.name}_v${variant.versionName}_${releaseTime()}.apk"
                    outputFileName = fileName
                }
            }
        }

        debug {
            //applicationIdSuffix ".BETA"
            versionNameSuffix "-BETA"
            minifyEnabled false
            shrinkResources false
            debuggable true
            testCoverageEnabled true
            signingConfig signingConfigs.release
        }
    }

    lintOptions {
        abortOnError false
    }

    compileOptions {
        sourceCompatibility javaSourceCompatibility
        targetCompatibility javaTargetCompatibility
    }

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    //noinspection GradleCompatible
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.legacy:legacy-support-v13:1.0.0'

    implementation 'com.jakewharton:butterknife:10.1.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

    implementation 'cc.cloudist.acplibrary:library:1.2.1'

    //DebugOverlay-Android
//    debugImplementation 'com.ms-square:debugoverlay:1.1.3'
//    releaseImplementation 'com.ms-square:debugoverlay-no-op:1.1.3'
//    testImplementation 'com.ms-square:debugoverlay-no-op:1.1.3'

    //Logger
    implementation 'com.orhanobut:logger:2.2.0'

    //libaums USB Mass Storage
    implementation 'com.github.mjdev:libaums:0.5.5'

    //PermissionGen
    implementation 'com.lovedise:permissiongen:0.1.1'

    //Android-SpinKit
    implementation 'com.github.ybq:Android-SpinKit:1.2.0'

    // FlexboxLayout
    implementation 'com.google.android:flexbox:1.0.0'

    // UVCCamera
    implementation("com.serenegiant:common:${commonLibVersion}") {
        exclude module: 'support-v4'
    }
    implementation project(':libuvccamera')
    implementation project(':usbCameraCommon')
}

static def releaseTime() {
    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}

updateVersion()

def updateVersion() {
    def propertiesFile = file('build.properties')
    Properties properties = readProperties(propertiesFile)

    def versionMajor = properties['version_major'].toString().toInteger()
    def versionMinor = properties['version_minor'].toString().toInteger()
    def versionPatch = properties['version_patch'].toString().toInteger()
    def versionBuild = properties['version_build'].toString().toInteger()
    def versionStore = properties['version_store'].toString().toInteger()

    if (isReleaseTask()) {
        System.out.println(">>> Building Release...")
        versionPatch++
        versionStore++
        versionBuild = 0
        properties['version_patch'] = versionPatch.toString()
        properties['version_store'] = versionStore.toString()
        properties['version_build'] = versionBuild.toString()
        writeProperties(propertiesFile, properties)
    }
    if (isCompileTask()) {
        System.out.println(">>> Compiling Source...")
        versionBuild++
        properties['version_build'] = versionBuild.toString()
        writeProperties(propertiesFile, properties)
    }

    def versionName = "${versionMajor}.${versionMinor}.${versionPatch}"
    def applicationId = android.defaultConfig.applicationId
    if (!isReleaseTask()) {
        versionName = versionName + ".${versionBuild}"
        applicationId = applicationId + android.buildTypes.debug.applicationIdSuffix
    }
    System.out.println(">>> " + project.parent.name + " " + versionName + " (" + versionStore + ") '" + applicationId + "'")
    android.defaultConfig.versionCode = versionStore
    android.defaultConfig.versionName = versionName
}

def isCompileTask() {
    def tasks = gradle.getStartParameter().getTaskNames()
    return ':app:generateDebugSources' in tasks || ':app:generateReleaseSources' in tasks ||
            'generateDebugSources' in tasks || 'generateReleaseSources' in tasks
}

def isReleaseTask() {
    def tasks = gradle.getStartParameter().getTaskNames()
    return ':app:assembleRelease' in tasks || 'assembleRelease' in tasks
}

static Properties readProperties(propertiesFile) {
    if (propertiesFile.canRead()) {
        Properties properties = new Properties()
        def inputStream = new FileInputStream(propertiesFile)
        properties.load(inputStream)
        inputStream.close()
        return properties
    } else {
        def message = ">>> Could not read " + propertiesFile.name + " file!"
        System.err.println(message)
        throw new GradleException(message)
    }
}

def static writeProperties(propertiesFile, properties) {
    def writer = propertiesFile.newWriter()
    properties.store(writer, "Build Properties")
    writer.close()
}