import java.text.SimpleDateFormat

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'com.google.gms.google-services'
    id 'com.google.firebase.crashlytics'
    id 'org.jetbrains.kotlin.kapt'
    id 'com.tencent.vasdolly'
    id 'kotlin-parcelize'
    id("com.dropbox.dependency-guard") version "0.5.0"
}

apply plugin: 'com.wenext.bundle.local.test'

def isEnableTrace = project.hasProperty("ENABLE_TRACE") && project.ENABLE_TRACE.toBoolean()
if (isEnableTrace) {
    apply plugin: "LancerTracePlugin"
}
println("isEnableTrace: " + isEnableTrace)

def isOfficial = project.OFFICIAL == "true"
if (!isOfficial) {
    apply from: "proguard-log.gradle"
}
println("isOfficial:" + isOfficial)
println("IS_RELEASE:" + project.IS_RELEASE)
//apply from: "aab_res_guard.gradle"

apply from: "zip-audio-to-assets.gradle"
apply from: "dependencyGuard.gradle"

def hookConfigByLocalProperties(String localKey, String defaultValue) {
    String config = readLocalProperties(localKey)
    if (config != null) {
        System.out.println("hookConfigByLocalProperties($localKey) ==> $config")
        return config
    }
    return defaultValue
}

def readLocalProperties(String key) {
    File file = rootProject.file('local.properties')
    if (file.exists()) {
        //加载资源
        InputStream inputStream = rootProject.file('local.properties').newDataInputStream();
        Properties properties = new Properties()
        properties.load(inputStream)
        if (properties.containsKey(key)) {
            return properties.getProperty(key)
        }
    }
    return null
}

android {
    namespace 'com.adealink.weparty'
    compileSdk libs.versions.compileSdk.get().toInteger()

    defaultConfig {
        applicationId "com.jiehe.gami"
        minSdk libs.versions.minSdk.get().toInteger()
        targetSdk libs.versions.targetSdk.get().toInteger()
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        resConfigs "zh", "en", "in"

        ndk {
            abiFilters "armeabi-v7a"
            abiFilters "arm64-v8a"
            debugSymbolLevel 'FULL'
        }
        //指定room.schemaLocation生成的文件路径  处理Room 警告 Schema export Error
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }


        def jvc = project.hasProperty('JKS_VERSION_CODE') ? project.JKS_VERSION_CODE : ""
        def jvn = project.hasProperty('JKS_VERSION_NAME') ? project.JKS_VERSION_NAME : ""
        def localVC = hookConfigByLocalProperties("VERSION_CODE", VERSION_CODE)
        def localVN = hookConfigByLocalProperties("VERSION_NAME", VERSION_NAME)
        def vc = jvc != "" ? project.JKS_VERSION_CODE.toInteger() : localVC.toInteger()
        def vn = jvn != "" ? project.JKS_VERSION_NAME : localVN
        println("version_code = " + vc)
        println("version_name = " + vn)

        versionCode vc
        versionName vn

        manifestPlaceholders = [
                fbAppId         : "",
                fbClientToken   : "",
                deepLinkScheme  : "gami",
                deepLinkHost    : "app",
                httpDeepLinkHost: "gami.vip"
        ]
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro', (isOfficial ? 'proguard-log-empty.pro' : 'proguard-log.pro')

        buildConfigField("boolean", "OFFICIAL", project.OFFICIAL)
        buildConfigField("boolean", "IS_RELEASE", hookConfigByLocalProperties("IS_RELEASE", IS_RELEASE))
        buildConfigField("String", "HTTPS_WEB_HOST", '"https://web.gami.vip"')

        buildConfigField("String", "QTT_APP_KEY", '"baa9f1307e2e8ee02742d960828b5c50"')
        buildConfigField("String", "HTTP_DEEP_LINK_HOST", '"web.gami.vip"')
        buildConfigField("String", "HTTP_DEBUG_DEEP_LINK_HOST", '"test-web.gami.vip"')

        buildConfigField("String", "DEEP_LINK_SCHEME", '"gami"')
        buildConfigField("String", "DEEP_LINK_HOST", '"app"')
        buildConfigField("String", "UTM_FACEBOOK_KEY", '"c4ea5534613d8b3cdcd5b80097989f9eb2414138aa8e49ddfbc458cd5e50f1a6"')

        //trtc
        buildConfigField("Integer", "TRTC_APP_ID", "80000456")
        //trtc debug
        buildConfigField("Integer", "TRTC_APP_ID_DEBUG", "20034873")

        //官方会话ID
        buildConfigField("String", "OFFICIAL_UID", "\"${OFFICIAL_UID}\"")
        buildConfigField("String", "OFFICIAL_CONVERSATION_ID", "\"${OFFICIAL_CONVERSATION_ID}\"")

        //sign key(业务登录)
        buildConfigField("String", "SIGN_KEY", '"abc|abc|edg|9527|1234"')
        buildConfigField("String", "SIGN_KEY_DEBUG", '"abc|abc|edg|9527|1234"')

        //Adjust
        buildConfigField("String", "ADJUST_TOKEN", '"fbze46mdkxds"')
    }

    signingConfigs {
        debug {
            keyAlias "gami"
            keyPassword "gami654321"
            storePassword "gami654321"
            storeFile file('../keystore/debug/gami-debug.jks')
        }
        release {
            keyAlias "gami"
            keyPassword "gami654321"
            storePassword "gami654321"
            storeFile file("../keystore/release/gami.jks")
        }
    }


    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.debug
            firebaseCrashlytics {
                mappingFileUploadEnabled false
            }
            applicationIdSuffix = '.debug'
            manifestPlaceholders = [
                    appName         : "@string/app_name",
                    appIcon         : "@drawable/ic_launcher"
            ]
        }
        release {
            debuggable false
            minifyEnabled false
            signingConfig signingConfigs.release
            manifestPlaceholders = [
                    appName         : "@string/app_name",
                    appIcon         : "@drawable/ic_launcher"
            ]
            firebaseCrashlytics {

                mappingFileUploadEnabled false
                nativeSymbolUploadEnabled false

//                mappingFileUploadEnabled !isOfficial
//                nativeSymbolUploadEnabled !isOfficial
//                strippedNativeLibsDir 'build/intermediates/stripped_native_libs/release/out/lib'
//                unstrippedNativeLibsDir 'build/intermediates/merged_native_libs/release/out/lib'
            }
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
        coreLibraryDesugaringEnabled true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17.majorVersion
    }
    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = false
        }
        abi {
            enableSplit = true
        }
    }
    sourceSets {
        main {
            jniLibs {
                srcDir 'libs'
            }
        }
    }
    packagingOptions {
        exclude '**/*.kotlin_*'
        exclude '**/values-*/strings.xml'
        pickFirst('lib/armeabi-v7a/libc++_shared.so')
        pickFirst('lib/arm64-v8a/libc++_shared.so')
        pickFirst('lib/x86/libc++_shared.so')
        pickFirst('lib/x86_64/libc++_shared.so')
    }
    dynamicFeatures = [
            ':module:account',
            ':module:profile',
            ':module:im',
            ':module:playmate',
            ':module:activity',
            ':module:setting',
            ':module:order',
            ':module:wallet',
            ':module:share',
            ':module:image',
            ':module:joinus',
            ':module:call',
            ':module:room',
            ':module:gift',
    ]
    buildFeatures {
        viewBinding true
        buildConfig true
    }
    configurations.configureEach {
        exclude group: 'com.facebook.fresco', module: 'drawee'
        exclude group: 'com.facebook.fresco', module: 'ui-core'
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
        disable 'Instantiatable'
    }


    android.applicationVariants.all { variant ->
        def variantNameCap = variant.name.capitalize()
        def taskName = "sign${variantNameCap}Bundle"

        def variantName = variant.name
        def flavorName = variant.flavorName
        def buildTypeName = variant.buildType.name

        tasks.named(taskName).configure { task ->
            def file = task.finalBundleFile.get().asFile
            def projectName = rootProject.name
            def versionCode = variant.versionCode
            def versionName = variant.versionName
            def timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())

            // 构造文件名：projectName-flavor-buildType-versionCode-versionName-timestamp.aab
            def nameParts = []
            nameParts << "app"
            nameParts << projectName

            if (flavorName) {
                nameParts << flavorName
            }

            nameParts << buildTypeName
            nameParts << "v${versionName}"
            nameParts << "(${versionCode})"
            nameParts << timestamp

            def finalFileName = "${nameParts.join('-')}.aab"

            def finalFile = new File(file.parentFile, finalFileName)
            task.finalBundleFile.set(finalFile)
        }
    }

}

gradle.taskGraph.addTaskExecutionListener(new TaskExecutionListener() {
    @Override
    void beforeExecute(Task task) {

    }

    @Override
    void afterExecute(Task task, TaskState taskState) {
        if (task.name.equalsIgnoreCase("bundleDebug")
                || task.name.equalsIgnoreCase("bundleRelease")) {

            copy {
                from 'build/intermediates/intermediary_bundle/'
                into 'build/outputs/bundle/'
                duplicatesStrategy DuplicatesStrategy.FAIL
            }

            println("afterExecute " + task.name)
            def aabDir = project.getBuildDir().absolutePath + '/outputs/bundle'
            fileTree(dir: aabDir, include: '*/*.aab').each { File file ->
                println(file.absolutePath)
                def cmd = []
                cmd << "java"
                cmd << "-jar"
                cmd << "${project.rootDir}/tool/bundletool.jar"
                cmd << "build-apks"
                cmd << "--bundle=" + file.absolutePath
                cmd << "--output=" + file.parent + File.separator + file.name.replace(".aab", "-split.apks")
                cmd << "--overwrite"
                cmd << "--mode=universal"
                if (task.name.equalsIgnoreCase("bundleDebug")) {
                    cmd << "--ks=" + android.signingConfigs.debug.storeFile
                    cmd << "--ks-pass=pass:" + android.signingConfigs.debug.storePassword
                    cmd << "--ks-key-alias=" + android.signingConfigs.debug.keyAlias
                    cmd << "--key-pass=pass:" + android.signingConfigs.debug.keyPassword
                } else {
                    def keystoreProperties = new Properties()
                    keystoreProperties.load(new FileInputStream(rootProject.file('keystore.properties')))
                    cmd << "--ks=" + keystoreProperties.storeFile
                    cmd << "--ks-pass=pass:" + keystoreProperties.storePassword
                    cmd << "--ks-key-alias=" + keystoreProperties.keyAlias
                    cmd << "--key-pass=pass:" + keystoreProperties.keyPassword
                }

                exec {
                    commandLine cmd
                }
            }
            println("after build apks")
        }
    }
})

configurations.configureEach {
    resolutionStrategy {
        // 方式1：强制指定所有 gson 依赖使用统一版本
//        force 'com.google.code.gson:gson:2.8.6'
//        // 方式2：遇到版本冲突时选择指定的版本
        eachDependency { DependencyResolveDetails details ->
            if (details.requested.group == 'com.google.code.gson' &&
                    details.requested.name == 'gson') {
                details.useVersion "2.8.6"
            }
        }
    }
}

dependencies {
    api fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
    //kotlin
    implementation libs.kotlin.stdlib
    coreLibraryDesugaring libs.desugar.jdk.libs

    //androidx
    api libs.androidx.core.ktx
    api libs.androidx.appcompat
    api libs.androidx.constraint.layout
    api libs.androidx.activity
    api libs.androidx.fragment.ktx
    api libs.androidx.viewpager2
    api libs.androidx.lifecycle.livedata.ktx
    api libs.androidx.lifecycle.viewmodel.ktx
    api libs.androidx.exifinterface
    implementation libs.androidx.multidex
    implementation libs.androidx.vectordrawable
    implementation libs.androidx.work.manager
    api libs.androidx.room.runtime
    api libs.androidx.room.ktx
    api libs.flexbox
    kapt libs.androidx.room.compiler
    implementation libs.androidx.camera.core
    implementation libs.androidx.camera.camera2
    implementation libs.androidx.camera.lifecycle
    implementation libs.androidx.camera.video
    implementation libs.androidx.camera.view
    api libs.androidx.webkit


    //android
    implementation libs.android.material
    implementation libs.android.install.referrer

    //google play core
    implementation libs.play.feature.delivery
    implementation libs.play.feature.delivery.ktx
    implementation libs.play.app.update
    implementation libs.play.app.update.ktx

    //facebook
    implementation libs.facebook.android.sdk

    //adjust
    implementation libs.adjust.android
    implementation libs.adjust.android.webbridge
    implementation libs.gms.play.services.ads.identifier

    //java
    implementation libs.rxjava

    //channel
    implementation libs.tencent.vasdolly.helper

    //firebase
    implementation platform(libs.firebase.bom)
    implementation libs.firebase.analytics
    implementation libs.firebase.crashlytics
    implementation libs.firebase.crashlytics.ndk
    implementation libs.firebase.dynamic.link
    implementation libs.firebase.messaging

    //gson
    implementation libs.gson

    //other
    api libs.smart.refresh.layout.kernel
    api libs.smart.refresh.header.material
    api libs.smart.refresh.footer.classics

    api libs.media3.exoplayer
    api libs.media3.exoplayer.dash
    api libs.media3.ui

    // media3 v1.4.1 guava 单独设置, 待media3更新后移除
    implementation libs.guava

    api libs.video.processor
    api libs.payermax
    api libs.rxjava

    //image
    api libs.compressor

    //tencent rtc
//    api libs.tencent.tui.core

    //frame
    api platform(libs.frame.bom)
//    api libs.frame.tcturing
    api libs.frame.animplayer
    api libs.frame.drawee
    api libs.frame.image
    api libs.frame.mvvm
    api libs.frame.util
    api libs.frame.zero
    api libs.frame.base
    api libs.frame.network
//    api project(":frame:network")
    api libs.frame.retrofit
    api libs.frame.oss
    api libs.frame.download
    api libs.frame.sound
    api libs.frame.game
    api libs.frame.autosize
    api libs.frame.spi
    api libs.frame.data
    api libs.frame.aab
    api libs.frame.coroutine
    api libs.frame.storage
    api libs.frame.log
    api libs.frame.statistics
//    api project(":frame:statistics")
    api libs.frame.googleservice
    //api project(":frame:googleservice")
    api libs.frame.deviceid
    api libs.frame.security
    api libs.frame.guide
    api libs.frame.effect
    //api project(":frame:effect")
    api libs.frame.svga
    api libs.frame.debug

    api project(":frame:room")
    api project(":frame:oss")
    api libs.frame.startup

    api libs.frame.locale
    //api libs.frame.push
    api libs.frame.media
    api libs.frame.share
    api libs.frame.dot
    api libs.frame.crash
    api libs.frame.apm
    api libs.frame.audio
    api libs.frame.router.annotation
    api libs.frame.router.api
    kapt libs.frame.router.compiler

    implementation libs.toolargetool
    annotationProcessor libs.auto.service

    implementation(libs.rangeseekbar)
    implementation libs.frame.zxing
    implementation libs.pinyin

    api libs.tencent.tui.core
    api libs.tencent.uikit.common
    api project(":timcommon")
    api project(":tuichat")
    implementation project(":tuiconversation")
    api libs.tencent.imsdk
    api 'com.google.auto.service:auto-service-annotations:1.1.1'
    //implementation project(":tuiroomkit")
    api libs.tencent.timpush
    api libs.tencent.timpush.fcm

    api libs.tencent.atomic.x

//    debugApi "com.tuzhenlei:crashhandler:1.0.1"
//    debugApi 'cat.ereza:customactivityoncrash:2.3.0'
//    debugImplementation "io.github.yvescheung:Uinspector:2.0.20"
//    debugImplementation "io.github.yvescheung:Uinspector-optional-viewmodel:2.0.20"
//    debugImplementation "io.github.yvescheung:Uinspector-optional-fresco:2.0.20"
//    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.10'

    //test
    testImplementation libs.junit
    androidTestImplementation libs.androidx.junit
    androidTestImplementation libs.androidx.espresso.core

    if (isEnableTrace) {
        implementation(libs.frame.trace.api)
    }

    api libs.flexbox
}


dependencyGuard {
    configuration("releaseRuntimeClasspath")
}