package com.ccwangluo.accelerator.utils

import kotlinx.coroutines.isActive
import timber.log.Timber
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.Socket
import java.net.UnknownHostException
import kotlin.coroutines.coroutineContext

object NetUtils {

    suspend fun tcpPing(url: String, port: Int, proxyPort: Int = 0): Long {
        var time = -1L
        for (k in 0 until 2) {
            val one = socketConnectTime(url, port, proxyPort)
            if (!coroutineContext.isActive) {
                break
            }
            if (one != -1L && (time == -1L || one < time)) {
                time = one
            }
        }
        return time
    }

    private fun socketConnectTime(url: String, port: Int, proxyPort: Int): Long {
        try {
            val socket = if (proxyPort == 0) {
                Socket()
            } else {
                Socket(Proxy(Proxy.Type.SOCKS, InetSocketAddress("127.0.0.1", proxyPort)))
            }
            val start = System.currentTimeMillis()
            socket.connect(InetSocketAddress(url, port))
            val time = System.currentTimeMillis() - start
            socket.close()
            return time
        } catch (e: UnknownHostException) {
            e.printStackTrace()
        } catch (e: IOException) {
            Timber.d("socketConnectTime IOException: $e")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return -1
    }
}