package com.sshproxy.vpn.vpn

object Tun2Socks {
    @Volatile
    private var loaded = false

    private var loadError: String? = null

    fun loadErrorMessage(): String? = loadError

    private fun ensureLoaded(): Boolean {
        if (loaded) {
            return true
        }
        synchronized(this) {
            if (loaded) {
                return true
            }
            loadError?.let { return false }
            return try {
                System.loadLibrary("tun2socks_jni")
                loaded = true
                true
            } catch (e: UnsatisfiedLinkError) {
                loadError = e.message ?: "libtun2socks_jni.so не найден в APK"
                false
            }
        }
    }

    fun start(
        context: android.content.Context,
        tunFd: Int,
        mtu: Int,
        socksHost: String,
        socksPort: Int
    ): Boolean {
        if (!ensureLoaded()) {
            return false
        }
        val configFile = java.io.File(context.cacheDir, "tun2socks.yml")
        return nativeStart(tunFd, mtu, socksHost, socksPort, configFile.absolutePath) == 0
    }

    fun stop() {
        if (!loaded) {
            return
        }
        runCatching { nativeStop() }
    }

    /** Pair of (received bytes, transmitted bytes) through the TUN interface. */
    fun getStats(): Pair<Long, Long>? {
        if (!ensureLoaded()) {
            return null
        }
        val values = nativeGetStats() ?: return null
        if (values.size < 2) {
            return null
        }
        return values[0] to values[1]
    }

    private external fun nativeStart(
        tunFd: Int,
        mtu: Int,
        socksHost: String,
        socksPort: Int,
        configPath: String
    ): Int

    private external fun nativeStop()

    private external fun nativeGetStats(): LongArray?
}
