/*
 * Copyright(c) 2020 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.romupgrade"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode
        versionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

    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 = "AutoUpgrade_${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 JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

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

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

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

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

    // Retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation('com.squareup.retrofit2:converter-gson:2.7.0') {
        exclude module: 'gson'
    }

    // FileDownloader
    implementation 'com.liulishuo.filedownloader:library:1.7.7'

    // Gson
    implementation 'com.google.code.gson:gson:2.8.5'

    // rxjava
    implementation "io.reactivex.rxjava2:rxjava:2.2.4"
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

    implementation 'cn.trinea.android.common:trinea-android-common:4.2.15'
}

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()
}
