plugins {
    id 'com.android.application'
    id 'com.google.protobuf'
    id 'com.google.gms.google-services'
    id 'kotlin-android'
    id 'kotlin-parcelize'
    id 'org.jetbrains.kotlin.android'
    id "dagger.hilt.android.plugin"
    id "org.jetbrains.kotlin.kapt"
    id "com.google.dagger.hilt.android"
}

def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

def defaultAppName = "ESP RainMaker"
def defaultTransport = "Both"
def defaultSecurity = "2"
def defaultPoP = ""
def defaultPrefix = "PROV_"
def defaultWiFiScanSrc = "Device"
def defaultSec2UsernameWifi = "wifiprov"
def defaultSec2UsernameThread = "threadprov"

def defaultClientId = "1h7ujqjs8140n17v0ahb4n51m2"

def defaultBaseUrl = "https://api.rainmaker.espressif.com"
def defaultClaimBaseUrl = "https://esp-claiming.rainmaker.espressif.com"

def defaultAuthUrl = "https://3pauth.rainmaker.espressif.com"
def defaultRedirectUri = "rainmaker://com.espressif.rainmaker/success"
def gitHubIdentityProvider = "GitHub"
def googleIdentityProvider = "Google"

def defaultDocUrl = "https://rainmaker.espressif.com/"
def defaultPrivacyUrl = "https://rainmaker.espressif.com/docs/privacy-policy.html"
def defaultTermsOfUseUrl = "https://rainmaker.espressif.com/docs/terms-of-use.html"

def defaultUserPool = "2"
def matterBuild = false
def defaultVendorId = "0x131B" // Espressif's vendor ID

def defaultChinaBaseUrl = "https://api2.rainmaker.espressif.com.cn"
def defaultChinaAuthUrl = "https://api2.rainmaker.espressif.com.cn"
def defaultChinaClientId = "6m3FgmvJSt4g6pDrHgfpYj"
def defaultChinaClaimBaseUrl = "https://claiming.rainmaker.espressif.com.cn"
def defaultChinaPrivacyUrl = "https://rainmaker.espressif.com/zh-hans/docs/privacy-policy-cn/"
def defaultChinaTermsOfUseUrl = "https://rainmaker.espressif.com/zh-hans/docs/terms-of-use-cn/"

// Please configure WeChat App id to support WeChat login for China region
def weChatIdForLogin = "your_we_chat_id"

def localProperties = new Properties()
localProperties.load(new FileInputStream(rootProject.file("local.properties")))

// Conditional plugin
if (localProperties.getProperty("isChinaRegion", "false") != "true") {
    apply plugin: 'com.google.firebase.crashlytics'
}

android {

    compileSdk 35

    defaultConfig {
        applicationId "com.espressif.rainmaker"
        minSdkVersion 27
        targetSdkVersion 35
        versionCode 181
        versionName "3.9.0 - ${getGitHash()}"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        buildConfigField "String", "GitHash", "\"${getGitHash()}\""

        resValue "string", "app_name", localProperties.getProperty("appName", defaultAppName)
        buildConfigField "String", "POP", '"' + localProperties.getProperty("POP", defaultPoP) + '"'

        def transport = localProperties.getProperty("transport", defaultTransport)
        if (transport == null) {
            throw new GradleException("Transport not found. Define transport in the local.properties file.")
        } else if (!transport.equalsIgnoreCase("SoftAP") && !transport.equalsIgnoreCase("BLE") && !transport.equalsIgnoreCase("Both")) {
            throw new GradleException("Invalid 'transport' value. Please check 'transport' value in local.properties file.")
        } else {
            buildConfigField "String", "TRANSPORT", '"' + transport + '"'
        }

        def security = localProperties.getProperty("security", defaultSecurity)
        if (security == null) {
            throw new GradleException("Security not found. Define security in the local.properties file.")
        } else if (!security.equalsIgnoreCase("0") && !security.equalsIgnoreCase("1") && !security.equalsIgnoreCase("2")) {
            throw new GradleException("Invalid 'security' value. Please check 'security' value in local.properties file.")
        } else {
            buildConfigField "String", "SECURITY", '"' + security + '"'
        }

        def wifiScanSrc = localProperties.getProperty("wifiScanSource", defaultWiFiScanSrc)
        if (wifiScanSrc == null) {
            throw new GradleException("WiFi scan source not found. Define it in the local.properties file.")
        } else if (!wifiScanSrc.equalsIgnoreCase("Device") && !wifiScanSrc.equalsIgnoreCase("Phone")) {
            throw new GradleException("Invalid 'wifiScanSource' value. Please check 'wifiScanSource' value in local.properties file.")
        } else {
            buildConfigField "String", "WIFI_SCAN_SRC", '"' + wifiScanSrc + '"'
        }

        buildConfigField "String", "SECURITY_2_USERNAME_WIFI", '"' + localProperties.getProperty("security2Username", defaultSec2UsernameWifi) + '"'
        buildConfigField "String", "SECURITY_2_USERNAME_THREAD", '"' + localProperties.getProperty("security2UsernameThread", defaultSec2UsernameThread) + '"'
        buildConfigField "String", "LOCAL_CONTROL_SECURITY_2_USERNAME", '"' + localProperties.getProperty("localControlSecurity2Username", defaultSec2UsernameWifi) + '"'

        buildConfigField "boolean", "isFilterPrefixEditable", localProperties.getProperty("isFilterPrefixEditable", "true")
        buildConfigField "String", "DEVICE_NAME_PREFIX", '"' + localProperties.getProperty("deviceNamePrefix", defaultPrefix) + '"'

        buildConfigField "boolean", "isQRCodeSupported", localProperties.getProperty("isQRCodeSupported", "true")
        buildConfigField "boolean", "isScheduleSupported", localProperties.getProperty("isScheduleSupported", "true")
        buildConfigField "boolean", "isSceneSupported", localProperties.getProperty("isSceneSupported", "true")
        buildConfigField "boolean", "isLocalControlSupported", localProperties.getProperty("isLocalControlSupported", "true")
        buildConfigField "boolean", "isNodeGroupingSupported", localProperties.getProperty("isNodeGroupingSupported", "true")
        buildConfigField "boolean", "isNodeSharingSupported", localProperties.getProperty("isNodeSharingSupported", "true")
        buildConfigField "boolean", "isAutomationSupported", localProperties.getProperty("isAutomationSupported", "true")
        buildConfigField "boolean", "isOtaSupported", localProperties.getProperty("isOtaSupported", "false")
        buildConfigField "boolean", "isMatterSupported", localProperties.getProperty("isMatterSupported", "false")
        buildConfigField "boolean", "isCommandResponseSupported", localProperties.getProperty("isCommandResponseSupported", "false")

        //---Enable Continuous Updates---//
        buildConfigField "boolean", "isContinuousUpdateEnable", localProperties.getProperty("isContinuousUpdateEnable", "true")

        def defaultInterval = localProperties.getProperty("continuosUpdateInterval", "100")
        buildConfigField 'int', 'continuosUpdateInterval', String.valueOf(defaultInterval)
        //-------------------------------//

        def clientId = localProperties.getProperty("clientId", defaultClientId)
        def authUrl = localProperties.getProperty("authUrl", defaultAuthUrl)
        def redirectUri = localProperties.getProperty("redirectUri", defaultRedirectUri)

        buildConfigField "String", "CLIENT_ID", '"' + clientId + '"'

        buildConfigField "String", "BASE_URL", '"' + localProperties.getProperty("baseUrl", defaultBaseUrl) + '"'
        buildConfigField "String", "CLAIM_BASE_URL", '"' + localProperties.getProperty("claimBaseUrl", defaultClaimBaseUrl) + '"'

        buildConfigField "String", "AUTH_URL", '"' + authUrl + '"'
        buildConfigField "String", "TOKEN_URL", '"' + authUrl + "/token" + '"'
        buildConfigField "String", "REDIRECT_URI", '"' + redirectUri + '"'

        def chinaClientId = localProperties.getProperty("chinaClientId", defaultChinaClientId)
        def chinaAuthUrl = localProperties.getProperty("chinaAuthUrl", defaultChinaAuthUrl)

        buildConfigField "boolean", "isChinaRegion", localProperties.getProperty("isChinaRegion", "false")
        buildConfigField "String", "CHINA_WE_CHAT_APP_ID", '"' + localProperties.getProperty("weChatId", weChatIdForLogin) + '"'
        buildConfigField "String", "CHINA_BASE_URL", '"' + localProperties.getProperty("chinaBaseUrl", defaultChinaBaseUrl) + '"'
        buildConfigField "String", "CHINA_AUTH_URL", '"' + chinaAuthUrl + '"'
        buildConfigField "String", "CHINA_TOKEN_URL", '"' + chinaAuthUrl + "/token" + '"'
        buildConfigField "String", "CHINA_CLIENT_ID", '"' + chinaClientId + '"'
        buildConfigField "String", "CHINA_CLAIM_BASE_URL", '"' + localProperties.getProperty("chinaClaimBaseUrl", defaultChinaClaimBaseUrl) + '"'
        buildConfigField "String", "CHINA_PRIVACY_URL", '"' + localProperties.getProperty("chinaPrivacyUrl", defaultChinaPrivacyUrl) + '"'
        buildConfigField "String", "CHINA_TERMS_URL", '"' + localProperties.getProperty("chinaTermsOfUseUrl", defaultChinaTermsOfUseUrl) + '"'

        def gitHubUrl = authUrl + "/authorize?identity_provider=" + gitHubIdentityProvider +
                "&redirect_uri=" + redirectUri + "&response_type=CODE&client_id=" + clientId
        def googleUrl = authUrl + "/authorize?identity_provider=" + googleIdentityProvider +
                "&redirect_uri=" + redirectUri + "&response_type=CODE&client_id=" + clientId

        buildConfigField "String", "GITHUB_URL", '"' + gitHubUrl + '"'
        buildConfigField "String", "GOOGLE_URL", '"' + googleUrl + '"'

        buildConfigField "String", "DOCUMENTATION_URL", '"' + localProperties.getProperty("docUrl", defaultDocUrl) + '"'
        buildConfigField "String", "PRIVACY_URL", '"' + localProperties.getProperty("privacyUrl", defaultPrivacyUrl) + '"'
        buildConfigField "String", "TERMS_URL", '"' + localProperties.getProperty("termsOfUseUrl", defaultTermsOfUseUrl) + '"'

        // Alexa App Linking Configurations
        buildConfigField "String", "ALEXA_CLIENT_ID", '"' + localProperties.getProperty("alexaClientId") + '"'
        buildConfigField "String", "ALEXA_CLIENT_SECRET", '"' + localProperties.getProperty("alexaClientSecret") + '"'
        buildConfigField "String", "ALEXA_REDIRECT_URL", '"' + localProperties.getProperty("alexaRedirectUrl") + '"'
        buildConfigField "String", "ALEXA_RM_CLIENT_ID", '"' + localProperties.getProperty("alexaRMClientId") + '"'
        buildConfigField "String", "SKILL_ID", '"' + localProperties.getProperty("skillId") + '"'
        buildConfigField "String", "SKILL_STAGE", '"' + localProperties.getProperty("skillStage") + '"'
        buildConfigField "String", "ALEXA_ACCESS_TOKEN_URL", '"' + localProperties.getProperty("alexaAccessTokenUrl") + '"'

        // User pool selection
        def userPool = localProperties.getProperty("userPool", defaultUserPool)
        buildConfigField "String", "USER_POOL", '"' + userPool + '"'

        // Vendor Id for Matter
        def vendorId = localProperties.getProperty("vendorId", defaultVendorId)
        buildConfigField 'int', 'VENDOR_ID', String.valueOf(vendorId)
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = "11"
    }

    buildFeatures {
        viewBinding true
        buildConfig = true
    }

    buildTypes {
        release {
            minifyEnabled false
            debuggable false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
        }
    }

    sourceSets {
        main {
            if (matterBuild) {
                jniLibs.srcDirs = ['third_party/connectedhomeip/libs/jniLibs']
            }
        }
    }

    lintOptions {
        disable 'UnspecifiedImmutableFlag'
    }

    namespace 'com.espressif.rainmaker'
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.21.9'
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}

dependencies {

    // Native libs
    implementation fileTree(dir: "third_party/connectedhomeip/libs", include: ["*.jar", "*.so"])
    implementation fileTree(dir: "src/main/libs", include: ["*.aar"])
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation libs.lifecycle.viewmodel.ktx
    implementation libs.lifecycle.runtime.ktx

    implementation libs.appcompat
    implementation libs.constraintlayout
    implementation libs.recyclerview
    implementation libs.swiperefreshlayout
    implementation libs.browser
    implementation libs.core.ktx
    implementation libs.work.runtime

    implementation libs.rxandroid
    implementation libs.adapter.rxjava2
    implementation libs.retrofit
    implementation libs.converter.gson
    implementation libs.logging.interceptor
    implementation libs.gson

    implementation libs.material
    implementation libs.tink.android
    implementation libs.protobuf.javalite

    implementation libs.kotlinx.coroutines.android
    implementation libs.kotlinx.coroutines.core
    implementation libs.kotlinx.coroutines.rx2
    implementation libs.kotlinx.coroutines.jdk8

    // Firebase
    implementation platform(libs.firebase.bom)
    implementation libs.firebase.messaging
    implementation libs.play.services.gcm

    if (localProperties.getProperty("isChinaRegion", "false") != "true") {
        implementation libs.firebase.analytics
        implementation libs.firebase.crashlytics
    }

    // Connected Home
    implementation libs.play.services.base
    implementation libs.play.services.home
    implementation libs.play.services.threadnetwork
    
    implementation libs.esp.idf.provisioning.android
    implementation libs.code.scanner
    implementation libs.mpandroidchart
    implementation libs.tapholdupbutton
    implementation libs.avloadingindicatorview
    implementation libs.holocolorpicker
    implementation libs.android.gif.drawable
    implementation libs.android.segmented
    implementation libs.eventbus
    implementation libs.jnanoid
    implementation libs.jwtdecode

    //crypto
    implementation libs.bcpkix.jdk15to18
    implementation libs.bcprov.jdk15to18

    // Play Core library for in-app updates
    implementation libs.app.update
    implementation libs.app.update.ktx

    // CameraX
    implementation libs.camera.core
    implementation libs.camera.camera2
    implementation libs.camera.lifecycle
    implementation libs.camera.view

    implementation libs.wechat.sdk.android.without.mta

    testImplementation libs.junit
    androidTestImplementation libs.runner
    androidTestImplementation libs.espresso.core

    // Room dependencies
    def room_version = "2.5.2"
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"

    // Hilt
    // https://dagger.dev/hilt/gradle-setup
    implementation 'com.google.dagger:hilt-android:2.44.2'
    implementation 'com.google.ar:core:1.35.0'
    kapt 'com.google.dagger:hilt-compiler:2.44.2'

    implementation 'org.jsoup:jsoup:1.15.4'

    def aws_version = '2.73.0'
    implementation("com.amazonaws:aws-android-sdk-kinesisvideo:$aws_version@aar") { transitive = true }
    implementation("com.amazonaws:aws-android-sdk-kinesisvideo-signaling:$aws_version@aar") { transitive = true }
    implementation("com.amazonaws:aws-android-sdk-kinesisvideo-webrtcstorage:$aws_version@aar") { transitive = true }
    implementation("com.amazonaws:aws-android-sdk-mobile-client:$aws_version@aar") { transitive = true }
    implementation("com.amazonaws:aws-android-sdk-auth-userpools:$aws_version@aar") { transitive = true }
    implementation("com.amazonaws:aws-android-sdk-auth-ui:$aws_version@aar") { transitive = true }

    implementation "io.getstream:stream-webrtc-android:1.1.2"
    implementation 'org.apache.commons:commons-lang3:3.9'
    implementation 'com.google.guava:guava:28.1-android'
    implementation 'org.awaitility:awaitility:4.2.0'

    implementation('org.glassfish.tyrus.bundles:tyrus-standalone-client:1.21') {
        exclude module: 'javax.inject'
    }
}
