package com.flashlink.vpn

import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileOutputStream

internal class TProxyService {
    external fun TProxyStartService(configStr: String, tunFd: Int)
    external fun TProxyStopService()
    external fun TProxyGetStats(): LongArray

    companion object {
        private const val TAG = "flashlink"

        init {
            try {
                System.loadLibrary("hev-socks5-tunnel")
            } catch (e: Exception) {
                Log.e(TAG, "load hev-socks5-tunnel err!")
            }
        }
    }

    private fun buildConfig(socksPort: Int): String {
        return buildString {
            append("tunnel:\n")
            append("  mtu: ${1500}\n")
            append("  ipv4: \n")
            append("socks5:\n")
            append("  port: $socksPort\n")
            append("  address: 127.0.0.1\n")
            append("  udp: 'udp'\n")
        }
    }

    fun startTunnel(context: Context, socksPort: Int, tunnelConfig: String?,  tunFd: Int) {
        val configStr = if(tunnelConfig.isNullOrEmpty()) buildConfig(socksPort) else tunnelConfig
        val configFileDir = context.cacheDir.absolutePath
        val configFileName = "hev-socks5-tunnel.yaml"
        val cfgFile = File(configFileDir, configFileName)
        try {
            FileOutputStream(cfgFile, false).use { fos ->
                fos.write(configStr.toByteArray())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        TProxyStartService("$configFileDir/$configFileName", tunFd)
    }

    fun stopTunnel() {
        try {
            TProxyStopService()
        } catch (e: Exception) {
            // Ignore exception
            Log.w(TAG, "TProxyStopService stopTunnel failed", e)
        }
    }

    fun getStats(): LongArray {
        return try {
            TProxyGetStats()
        } catch (e: Exception) {
            Log.w(TAG, "TProxyGetStats failed, returning empty array", e)
            LongArray(0)
        }
    }
}
