/*
 * Copyright (c) 2021 DuckDuckGo
 *
 * 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.
 */

plugins {
    id 'com.android.library'
    id 'kotlin-android'
    id 'com.squareup.anvil'
}

apply from: "$rootProject.projectDir/gradle/android-library.gradle"

def getConfigPatchFiles() {
    def patchFiles = ""

    // check for local.properties file in this module first
    def localPropertiesFile = project.file('local.properties')
    if (localPropertiesFile.exists()) {
        def localProperties = new Properties()
        localPropertiesFile.withInputStream { localProperties.load(it) }
        
        if (localProperties.getProperty('config_patches')) {
            patchFiles = localProperties.getProperty('config_patches').toString()
            println "Using config patches from privacy-config-internal/local.properties: $patchFiles"
        }
    }
    
    // command line parameter takes precedence over local.properties
    if (project.rootProject.hasProperty('config_patches')) {
        patchFiles = project.rootProject.property('config_patches').toString()
        println "Using config patches from command line parameter: $patchFiles"
    }
    
    return patchFiles
}

android {
    anvil {
        generateDaggerFactories = true // default is false
    }
    lintOptions {
        baseline file("lint-baseline.xml")
        abortOnError = !project.hasProperty("abortOnError") || project.property("abortOnError") != "false"
    }
    namespace 'com.duckduckgo.privacy.config.internal'

    buildFeatures {
        buildConfig = true
    }

    defaultConfig {
        def patchFiles = getConfigPatchFiles()
        def patchFileNames = []

        if (patchFiles) {
            patchFiles.split(',').each { patchFilePath ->
                def patchFile = new File(patchFilePath.trim())
                if (patchFile.exists()) {
                    def fileName = patchFile.getName()
                    if (patchFileNames.contains(fileName)) {
                        throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.")
                    }
                    patchFileNames.add(fileName)
                } else {
                    println "Config patch file not found: ${patchFile.absolutePath}"
                }
            }
        }
        
        buildConfigField "String", "CONFIG_PATCHES", "\"${patchFileNames.join(',')}\""
    }
}

dependencies {
    anvil project(path: ':anvil-compiler')
    implementation project(path: ':anvil-annotations')
    implementation project(path: ':privacy-config-api')
    implementation project(path: ':privacy-config-impl')
    implementation project(path: ':privacy-config-store')
    implementation project(path: ':di')
    implementation project(path: ':common-utils')
    implementation project(path: ':design-system')
    implementation project(path: ':browser-api')

    implementation AndroidX.core.ktx

    implementation AndroidX.appCompat
    implementation AndroidX.lifecycle.viewModelKtx
    implementation AndroidX.lifecycle.runtime.ktx
    implementation Google.android.material
    implementation AndroidX.constraintLayout
    implementation Square.okHttp3.okHttp
    
    // Dagger
    implementation Google.dagger

    implementation "com.squareup.logcat:logcat:_"
    implementation "io.github.vishwakarma:zjsonpatch:_"
}

tasks.register('copyConfigPatches') {
    def buildAssetsDir = layout.buildDirectory.dir("generated/assets/configPatches").get().asFile
    def patchFiles = getConfigPatchFiles()
    
    doLast {
        // always clean up any existing patch files first, also ensures that when patching is disabled, the directory is cleaned up
        if (buildAssetsDir.exists()) {
            buildAssetsDir.listFiles().each { file ->
                if (file.name.endsWith('.json')) {
                    file.delete()
                    println "Removed old patch file from build assets: ${file.absolutePath}"
                }
            }
            if (buildAssetsDir.listFiles().length == 0) {
                buildAssetsDir.delete()
            }
        }

        if (patchFiles) {
            def fileNames = []
            patchFiles.split(',').each { patchFilePath ->
                def patchFile = new File(patchFilePath.trim())
                if (patchFile.exists()) {
                    def fileName = patchFile.getName()
                    if (fileNames.contains(fileName)) {
                        throw new GradleException("Duplicate patch file name detected: '$fileName'. Patch files must have unique names even if they are in different directories.")
                    }
                    fileNames.add(fileName)

                    if (!buildAssetsDir.exists()) {
                        buildAssetsDir.mkdirs()
                    }

                    def destFile = new File(buildAssetsDir, fileName)
                    destFile.bytes = patchFile.bytes
                    println "Copied config patch to build assets: ${patchFile.absolutePath} -> ${destFile.absolutePath}"
                } else {
                    println "Warning: Config patch file not found: ${patchFile.absolutePath}"
                }
            }
        }
    }
}

android.sourceSets.main.assets.srcDirs += layout.buildDirectory.dir("generated/assets/configPatches").get().asFile.path

afterEvaluate {
    tasks.matching { it.name.contains('mergeAssets') }.configureEach { task ->
        task.dependsOn copyConfigPatches
    }

    tasks.matching { it.name.contains('preBuild') }.configureEach { task ->
        task.dependsOn copyConfigPatches
    }

    // force the task to always run (never up-to-date)
    copyConfigPatches.outputs.upToDateWhen { false }
}
