plugins {
    alias libs.plugins.android.library
    alias libs.plugins.kotlin.android
}

android {
    namespace 'ir.erfansn.artouch.producer'
    compileSdk sdk.versions.compile.get().toInteger()

    defaultConfig {
        minSdk sdk.versions.min.get().toInteger()

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-fexceptions", "-frtti"
                abiFilters "arm64-v8a"

                def opencvSdkPath = obtainOpenCvSdkDirPath()
                arguments = [
                    "-DOpenCV_DIR=$opencvSdkPath/sdk/native/jni",
                    "-DANDROID_STL=c++_shared",
                    "-DANDROID_ARM_NEON=TRUE",
                ]
            }
        }
        ndkVersion = "25.2.9519653"
    }

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

            externalNativeBuild.cmake.arguments "-DCMAKE_BUILD_TYPE=Release"
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = '17'
    }

    externalNativeBuild {
        cmake {
            path file('./src/main/cpp/CMakeLists.txt')
            version '3.22.1'
        }
    }

    testOptions {
        // Only for Logging APIs
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    implementation project(':common')

    implementation libs.androidx.core
    implementation libs.androidx.camera.core
    implementation libs.google.mediapipe.tasks.vision
    implementation libs.kotlinx.coroutines.asProvider()
    implementation libs.io.insert.koin.asProvider()

    testImplementation libs.junit4
    testImplementation libs.kotlinx.coroutines.test
    androidTestImplementation libs.androidx.test.runner
    androidTestImplementation libs.androidx.test.core
    androidTestImplementation libs.kotlinx.coroutines.test
}

def obtainOpenCvSdkDirPath() {
    def opencvProperties = new Properties()
    def opencvPropertiesFile = rootProject.file('opencv.properties')
    if (!opencvPropertiesFile.exists()) {
        opencvPropertiesFile.createNewFile()
    }
    try (FileInputStream file = new FileInputStream(opencvPropertiesFile)) {
        opencvProperties.load(file)
    }
    if (opencvProperties['sdk.dir'] == null) {
        throw IllegalArgumentException(
                "Download Android OpenCV sdk from offical site then set its location " +
                        "to 'sdk.dir' propertiy inside opencv.properties file in root project"
        )
    }
    return opencvProperties['sdk.dir']
}
