import com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask
import java.nio.file.Files
import java.nio.file.StandardCopyOption

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.frolo.plugin.bundle_check'
apply plugin: 'com.frolo.plugin.task_utils'

def version_code = 178
def version_major = 7
def version_minor = 3
def version_patch = 8
def version_name = "${version_major}.${version_minor}.${version_patch}"

def script_time = new Date().format('MM.dd.yyyy:HH.mm.ss')
def google_services_properties_file = new File(project.projectDir, "google-services.properties")
def google_services_properties =
        optionallyLoadProperties(google_services_properties_file.absolutePath)
def google_services_enabled =
        google_services_properties['com.frolo.muse.google_services_enabled'] == 'true'
def local_properties = loadLocalProperties(project)

android {
    namespace = 'com.frolo.muse'
    signingConfigs {
        release {
            def configDir = getReleaseConfigDir()
            def releaseConfigs = loadProperties("$configDir/signing.properties")
            storeFile file("$configDir/${releaseConfigs['storeFile']}")
            storePassword releaseConfigs['storePassword']
            keyAlias releaseConfigs['keyAlias']
            keyPassword releaseConfigs['keyPassword']
        }
    }
    compileSdkVersion versions.compileSdk
    buildToolsVersion "30.0.3"
    defaultConfig {
        applicationId "com.frolo.musp"
        minSdkVersion versions.minSdk
        targetSdkVersion versions.targetSdk
        versionCode version_code
        versionName version_name
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
        multiDexEnabled true

        resValue "string", "app_name", "Frolomuse"

//        resValue "string", "admob_app_id", local_properties["com.admob.app_id"] ?: ""
//        resValue "string", "admob_unit_id_library_screen", local_properties["com.admob.unit_id.library_banner"] ?: ""

//        resValue "string", "facebook_ads_app_id", local_properties["com.facebook.ads.app_id"] ?: ""
//        resValue "string", "facebook_ads_placement_id", local_properties["com.facebook.ads.placement_id"] ?: ""
//        resValue "string", "facebook_ads_placement_id", local_properties["com.facebook.ads.placement_id"] ?: ""

        buildConfigField "Boolean", "GOOGLE_SERVICES_ENABLED", "$google_services_enabled"
        buildConfigField "String", "BUILD_SCRIPT_TIME", "\"${script_time}\""
        buildConfigField "String", "DEVELOPER_EMAIL", "\"alexei.artsimovich@gmail.com\""
        buildConfigField "Integer", "SOUND_WAVEFORM_LENGTH", "65"

        vectorDrawables.useSupportLibrary = true

        resConfigs "de", "en", "es", "fr", "hi", "in", "ja", "pt", "ru", "tr", "zh", "uk", "ko"

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

        kapt {
            arguments {
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }
    buildTypes {
        debug {
            applicationIdSuffix ".dbg"
            debuggable true
            shrinkResources false
            minifyEnabled false
            resValue "string", "app_name", "Dev Frolomuse"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            versionNameSuffix "-D"
        }

        release {
            shrinkResources true
            minifyEnabled true
            resValue "string", "app_name", "Frolomuse"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            versionNameSuffix "-R"
            signingConfig signingConfigs.release
        }
    }

    flavorDimensions "default"
    productFlavors {
        // Version for Play Store
        playStore {
        }

        // Version for App Gallery
        appGallery {
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all {
            outputFileName = "Frolomuse-${variant.name}-${version_name}.apk"
        }
    }

    lintOptions {
        checkReleaseBuilds true
        abortOnError true
        lintConfig file("$projectDir/lint.xml")
        baseline file("lint-baseline.xml")
    }

    sourceSets {
        main {
        }

        test {
            java.srcDirs += "$projectDir/src/testShared"
        }

        androidTest {
            java.srcDirs += "$projectDir/src/testShared"
        }
    }

    packagingOptions {
        exclude 'META-INF/api_debug.kotlin_module'
        exclude 'META-INF/api_release.kotlin_module'
    }

    buildFeatures {
        viewBinding true
    }
}

kotlin {
    jvmToolchain(buildtools.versions.java.get().toInteger())
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(buildtools.versions.java.get()))
    }
}

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

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    // https://stackoverflow.com/questions/74180208/kotlin-1-7-10-with-dagger-a-failure-occurred-while-executing-org-jetbrains-kotl
    kapt deps.jetbrains.kotlinxMetadataJvm

    // Ads
//    implementation project(path: ':ads:admob')
//    implementation 'com.facebook.android:audience-network-sdk:6.13.7'

    // Features
    implementation project(path: ':feature:onboarding')
    implementation project(path: ':feature:audiofx2')
    implementation project(path: ':feature:visualizer')

    // Core
    implementation project(path: ':core')

    // Music data
    implementation project(path: ':music-data:model')
    implementation project(path: ':music-data:repository:api')
    implementation project(path: ':music-data:repository:android-impl')
    implementation project(path: ':music-data:mediascan')

    // Player
    // TODO: remove once all users have migrated to AudioFx2
    implementation project(path: ':audio:audiofx:api')
    implementation project(path: ':audio:audiofx:android-impl')
    implementation project(path: ':audio:player:api')
    implementation project(path: ':audio:player:android-impl')
    implementation project(path: ':audio:player:data')
    implementation project(path: ':audio:audiofx2:api')
    implementation project(path: ':audio:audiofx2:android-impl')

    // Billing
    implementation project(path: ':billings:billing-api')
    playStoreImplementation project(path: ':billings:play-store-billing-impl')
    appGalleryImplementation project(path: ':billings:app-gallery-billing-impl')

    // Performance
    implementation project(path: ':performance:coldstart')
    implementation project(path: ':performance:anr')
    implementation project(path: ':performance:scroll')

    // Design
    implementation project(path: ':core-ui')
    implementation project(path: ':material-support')

    // Custom views
    implementation project(path: ':custom-view::equalizerview')
    implementation project(path: ':custom-view::mediabutton')

    // Custom drawables
    implementation project(path: ':custom-drawable:squircle')

    // Logger
    implementation project(path: ':logger:api')
    implementation project(path: ':logger:impl')

    // Utils
    implementation project(path: ':utils:collections')
    implementation project(path: ':utils:debug-common')
    implementation project(path: ':utils:threads-common')
    implementation project(path: ':utils:rx')
    implementation project(path: ':utils:ui')
    implementation project(path: ':utils:stopwatch')
    implementation project(path: ':utils:headset')

    // Vendor
    implementation project(path: ':vendor')

    // Audio libs
    implementation project(path: ':audio-libs:my_id3')
    //implementation group: 'org', name: 'jaudiotagger', version: '2.0.3' // https://mvnrepository.com/artifact/org/jaudiotagger
    implementation project(path: ':audio-libs:soundwaveform')
    implementation project(path: ':audio-libs:ringdroid')

    def mockito_version = "3.10.0" // 2.23.0
    def mockito_kotlin_version = "2.1.0"
    // Instrumentation tests
    androidTestImplementation deps.test.runner
    androidTestImplementation "org.mockito:mockito-core:$mockito_version"
    androidTestImplementation "org.mockito:mockito-android:$mockito_version"
    androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin_version"
    androidTestImplementation project(path: ':test-tools:stubs')
    androidTestImplementation project(path: ':test-tools:assets')

    // Unit tests
    testImplementation 'junit:junit:4.13.2'
    testImplementation "org.mockito:mockito-core:$mockito_version"
    testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin_version"
    testImplementation deps.support.coreTesting
    testImplementation project(path: ':test-tools:stubs')

    // Arch
    implementation deps.lifecycle.extensions
    implementation deps.lifecycle.viewmodel
    kapt deps.lifecycle.compiler
    implementation project(path: ':arch-support')

    // Support
    implementation deps.support.multidex
    implementation deps.support.appCompat
    implementation deps.support.fragment
    implementation deps.support.media
    implementation deps.support.core
    implementation deps.support.preferences

    // Design
    implementation deps.design.material
    implementation deps.design.recyclerView
    implementation deps.design.cardView
    implementation deps.design.constraintLayout
    implementation deps.design.dynamicAnimation
    implementation deps.design.viewPager2
    implementation deps.design.palette
    implementation deps.design.flexbox

    // Room
    implementation deps.room.runtime
    implementation deps.room.rxJava2
    kapt deps.room.compiler

    // RxJava2
    implementation deps.rxJava2.rxJava
    implementation deps.rxJava2.rxAndroid

    // DI
    compileOnly deps.javax.annotationApi
    implementation deps.di.dagger
    kapt deps.di.daggerCompiler

    // Firebase
    implementation platform(deps.firebase.bom)
    implementation deps.firebase.core
    implementation deps.firebase.crashlytics
    implementation deps.firebase.config
    implementation deps.firebase.messaging

    // Glide
    implementation deps.glide.glide
    implementation deps.glide.transformations
    kapt deps.glide.compiler

    // Fragment navigation
    implementation 'com.github.ncapdevi:fragnav:3.3.0'
    // Sticky headers recycler view
    implementation 'com.timehop.stickyheadersrecyclerview:library:0.4.3@aar'
    // Alphabet index fast scroller
    implementation 'io.github.l4digital:fastscroll:2.1.0'
    // Runtime permissions
    implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
    // RxAdapter for ContentResolver and SharedPreferences
    implementation 'com.github.alexei-frolo:RxContent:1.0.3'
    // Circular Progress Bar
    implementation 'com.mikhaellopez:circularprogressbar:3.1.0'
    // Gesture Image View
    implementation 'com.alexvasilkov:gesture-views:2.6.0'
    // Jsoup (HTML parser)
    implementation 'org.jsoup:jsoup:1.13.1'
    // Tooltips
    implementation 'com.github.sephiroth74:android-target-tooltip:release-1.3.15'
    // Waveform Seek Bar
    implementation 'com.github.alexei-frolo:WaveformSeekBar:1.1'
    // Falling snow view
    implementation 'com.github.jetradarmobile:android-snowfall:1.2.1'
    // Lottie animation
    implementation 'com.airbnb.android:lottie:4.2.2'
}

if (google_services_enabled) {
    apply plugin: 'com.google.firebase.crashlytics'
    apply plugin: 'com.google.gms.google-services'
}

if (project.hasProperty('kapt')) {
    // Reference for 'kapt' DSL: https://kotlinlang.org/docs/reference/kapt.html#java-compiler-options
    kapt {
        // we expect this closure to run over a org.jetbrains.kotlin.gradle.plugin.KaptExtension
        javacOptions {
            option("--source", "8")
            option("--target", "8")
            option("-source", "8")
            option("-target", "8")
        }
    }
}

afterEvaluate {
    // https://developer.android.com/tools/aapt2
    tasks.withType(LinkApplicationAndroidResourcesTask).configureEach {
        // stableIdsOutputFileProperty.orNull?.asFile
        def variantName = it.variantName

        def stableIdsFileDir = new File(buildDir, "intermediates/stable_resource_ids_file/$variantName")
        def stableIdsFile = new File(stableIdsFileDir, "stableIds.txt")

        def persistentStableIdsFileDir = new File(projectDir, "stable_resource_ids_file/$variantName")
        def persistentStableIdsFile = new File(persistentStableIdsFileDir, "stableIds.txt")

        if (!stableIdsFile.exists() && persistentStableIdsFile.exists()) {
            stableIdsFileDir.mkdirs()
            Files.copy(
                    persistentStableIdsFile.toPath(),
                    stableIdsFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING)
        }
        doLast {
            persistentStableIdsFileDir.mkdirs()
            if (stableIdsFile.exists()) {
                Files.copy(
                        stableIdsFile.toPath(),
                        persistentStableIdsFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING)
            }
        }
    }
}

afterEvaluate {
    tasks.findByName("bundlePlayStoreRelease").configure {
        def testTask = tasks.findByName("testPlayStoreReleaseUnitTest")
        testTask.configure {
            // Check that the res ids has not changed
            it.filter.includeTest("com.frolo.muse.CheckPlayStoreReleaseResIdsTest", "checkResIds")
        }
        it.finalizedBy(testTask)
    }
}
