int MILLIS_IN_MINUTE = 1000 * 60
int minutesSinceEpoch = System.currentTimeMillis() / MILLIS_IN_MINUTE

def safeExtGet(prop, fallback) {
    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}

def isNewArchitectureEnabled() {
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

def supportsNamespace() {
  def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
  def major = parsed[0].toInteger()
  def minor = parsed[1].toInteger()

  // Namespace support was added in 7.3.0
  if (major == 7 && minor >= 3) {
    return true
  }

  return major >= 8
}

def checkProjectInfo() {
    def hasExpoModulesCore = rootProject.subprojects.any { it.name == 'expo-modules-core' }
    def packageJsonFile = new File(rootProject.projectDir.parentFile, 'package.json')
    
    def hasExpoDependency = false
    def projectVersion = '1.0.0' // Default version

    if (packageJsonFile.exists()) {
        def packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
        projectVersion = packageJson.version ?: '1.0.0' // Get project version

        // Check for expo dependency and version >= 50
        String expoVersionString = packageJson.dependencies?.expo ?: packageJson.devDependencies?.expo
        boolean expoVersionIsHighEnough = false
        if (expoVersionString) {
            try {
                // Extract the first number sequence as the major version
                def matcher = (expoVersionString =~ /(\d+)/)
                if (matcher.find()) {
                    int majorVersion = matcher[0][0].toInteger()
                    if (majorVersion >= 50) {
                        expoVersionIsHighEnough = true
                    }
                }
            } catch (NumberFormatException e) {
                // Handle error if version parsing fails, maybe log a warning
                println "Warning: Could not parse Expo version string: ${expoVersionString}"
            }
        }
        hasExpoDependency = expoVersionIsHighEnough // Update based on version check
    }
    
    def isExpo = hasExpoModulesCore && hasExpoDependency
    
    // Return a map containing both pieces of information
    return [isExpo: isExpo, version: projectVersion]
}

// Get project info map
def projectInfo = checkProjectInfo()
// Extract info into variables
def projectVersion = projectInfo.version
def expoProject = projectInfo.isExpo

apply plugin: 'com.android.library'
if (isNewArchitectureEnabled()) {
    apply plugin: 'com.facebook.react'
}

if (expoProject) {
    group = 'expo.modules.pushy'
    version = projectVersion

    def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
    apply from: expoModulesCorePlugin
    applyKotlinExpoModulesCorePlugin()
    // useExpoPublishing()
    useCoreDependencies()
} else {
    group = 'cn.reactnative.modules.update'
    version = projectVersion
}

android {
    if (supportsNamespace()) {
        namespace "cn.reactnative.modules.update"

        sourceSets {
            main {
                manifest.srcFile "src/main/AndroidManifestNew.xml"
            }
        }
    }
    compileSdkVersion safeExtGet('compileSdkVersion', 28)
    buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3')
    defaultConfig {
        minSdkVersion safeExtGet('minSdkVersion', 16)
        targetSdkVersion safeExtGet('targetSdkVersion', 27)
        versionCode 1
        versionName "1.81.4"
        consumerProguardFiles "proguard.pro"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
    }
    
    sourceSets {
        main {
            // let gradle pack the shared library into apk
            jniLibs.srcDirs = ['./lib']
            if (isNewArchitectureEnabled()) {
                java.srcDirs += ['src/newarch']
            } else {
                java.srcDirs += ['src/oldarch']
            }
            
            if (expoProject) {
                java.srcDirs += ['java/expo/modules/pushy']
            } else {
                java.exclude 'expo/modules/pushy/**'
            }
        }
    }

    buildTypes {
        release {
            resValue("string", "pushy_build_time", "${minutesSinceEpoch}")
        }
        debug {
            resValue("string", "pushy_build_time", "0")
        }
    }
    
    lintOptions {
        abortOnError false
    }
}

repositories {
    maven {
        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
}

dependencies {
    implementation 'com.facebook.react:react-native:+'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
}
if (isNewArchitectureEnabled()) {
    react {
        jsRootDir = file("../lib/")
        libraryName = "update"
        codegenJavaPackageName = "cn.reactnative.modules.update"
    }
}
