package com.github.shadowsocks.bg

import android.net.Network
import com.ccnet.acc.AccVpn
import com.ccnet.acc.NetworkAdapter
import com.github.shadowsocks.Core
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.database.ProfileManager
import com.github.shadowsocks.http.*
import com.github.shadowsocks.preference.DataStore
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import timber.log.Timber
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager

object AuthManager {

    val executor = Executors.newScheduledThreadPool(1)
    var scheduleAtFixedRate: ScheduledFuture<*>? = null
    var scheduleAtFixedRate1: ScheduledFuture<*>? = null

    val mmkv = MMKV.mmkvWithID("InterProcessKV", MMKV.MULTI_PROCESS_MODE)

    private const val KEY_TOKEN = "com.ccwangluo.KEY_TOKEN"


    var gameId: String?
        get() = mmkv.decodeString("CONFIG_GAMEID", null)
        set(gameId) {
            mmkv.putString("CONFIG_GAMEID", gameId)
        }
    var area: String?
        get() = mmkv.decodeString("CONFIG_AREA", null)
        set(gameId) {
            mmkv.putString("CONFIG_AREA", gameId)
        }

    var authToken: String?
        get() = mmkv.decodeString(KEY_TOKEN, null)
        set(token) {
            mmkv.putString(KEY_TOKEN, token)
        }

    // 加速时长
    var ACC_TIME: Long
        get() = mmkv.decodeLong("ACC_TIME", 0L)
        set(acc_time) {
            mmkv.putLong("ACC_TIME", acc_time)
        }

    var Last_ACC_TIme: Long
        get() = mmkv.decodeLong("LAST_ACC_TIME", 0L)
        set(last_acc_time) {
            mmkv.putLong("LAST_ACC_TIME", last_acc_time)
        }

    /**
     * 智能加速是否启动
     */
    var isSmartAccOpen: Boolean
        get() = mmkv.decodeBool("IS_SMART_ACC_OPEN", true)
        set(isSmartAccOpen) {
            mmkv.putBoolean("IS_SMART_ACC_OPEN", isSmartAccOpen)
        }

    class AuthException(msg: String) : IOException(msg), BaseService.ExpectedException

    var isreload = false

    private var currentNetwork: Int = -1


    suspend fun initAuthProfile(profile: Profile) {
        withContext(Dispatchers.IO) {
            val gameId: Int = gameId?.toInt() ?: throw AuthException("游戏不存在")
            val lineConfigResult = HttpUtils.postSync<LineConfig>(
                "/api/acc/line",
                authToken,
                LineConfigReq(gameId, area)
            )
            if (lineConfigResult.isSuccessful()) {
                val lineConfig = lineConfigResult.unwrapData()
                profile.host = lineConfig.host
                profile.token = lineConfig.token
                profile.remotePort = lineConfig.port

                DataStore.pingProxyServer = profile.host
                DataStore.pingProxyPort = profile.remotePort + 1
                Timber.d("start vpn with games: ${profile.individual}, profileId: ${profile.id}, route: ${profile.route}")
                ProfileManager.updateProfile(profile)
            } else if (lineConfigResult.code == 1001) {
                throw AuthException(lineConfigResult.error!!)
            } else {
                throw AuthException(lineConfigResult.error!!)
            }
        }
    }

    fun updateConfig(data: BaseService.Data) {
        Timber.d("updateConfig  ${data.state.name}  + $isreload")
        if (data.state == BaseService.State.Connected) {
            if (!isreload) {
                ACC_TIME = System.currentTimeMillis()
            } else {
                isreload = false
            }
        } else {
            if (!isreload) {
                ACC_TIME = 0L
                Last_ACC_TIme = System.currentTimeMillis()
            }
            return
        }
        NetworkAdapter.initNetworks(Core.app)
        scheduleAtFixedRate?.cancel(false)
        var failedCount: Int = 0
        scheduleAtFixedRate = executor.scheduleAtFixedRate({
            if (data.state == BaseService.State.Connected) {
                data.proxy?.let { proxyInstance ->
                    val refreshTokenResult = HttpUtils.postSync<RefreshTokenRes>(
                        "/api/acc/line/refresh", authToken,
                        RefreshTokenReq(proxyInstance.profile.token ?: "")
                    )
                    Timber.d("refreshTokenResult: $refreshTokenResult")
                    if (refreshTokenResult.isSuccessful()) {
                        failedCount = 0
                        proxyInstance.profile.token = refreshTokenResult.unwrapData().token
                        data.tunFd?.let {
                            AccVpn.writeConfig(Core.app, it, proxyInstance.profile)
                        }
                        return@let
                    } else if (refreshTokenResult.code == 1001) {
                        failedCount = 0
                        throw AuthException(refreshTokenResult.error!!)
                    } else {
                        failedCount++;
                        //连续失败超过3次抛异常
                        if (failedCount >= 3) {
                            failedCount = 0
                            throw AuthException("网络异常")
                        }
                    }
                }
            }

        }, 1, 1, TimeUnit.MINUTES)
        scheduleAtFixedRate1?.cancel(false)
        scheduleAtFixedRate1 = executor.scheduleAtFixedRate(
            {
                Timber.d("testLatency")
                GlobalScope.launch {
                    if (data.state == BaseService.State.Connected) {
                        testLatency()
                        if (wifiLatencyList.size == 5 && data.state == BaseService.State.Connected) {
                            val wifiavg = wifiLatencyList.average().toInt()
                            val celavg = cellularLatencyList.average().toInt()
                            if (wifiavg > celavg && wifiavg > 200 && celavg != -1 && currentNetwork < 0) {
                                currentNetwork = 0
                                NetworkAdapter.useCellular(Core.deviceStorage)
                                isreload = true
                                Core.reloadService()
                                Timber.d("switch to cellular")
                            }
//                        else if (celavg > wifiavg && wifiavg != -1) {
//                            NetworkAdapter.useWifi(Core.deviceStorage)
//                            isreload = true
//                            Core.reloadService()
//                            Timber.d("switch to wifi")
//                        }
                        }
                    }
                    wifiLatencyList.clear()
                    cellularLatencyList.clear()
                }
            },
            5,
            5,
            TimeUnit.SECONDS
        )
    }

    private val wifiLatencyList = mutableListOf<Int>()
    private val cellularLatencyList = mutableListOf<Int>()

    private suspend fun testLatency() {
        val networkAutoSwitch =
            isSmartAccOpen // 根据用户设置测试延迟 ，过高时切换 connection.bindNetwork(NetworkMode.CELLULAR.code)
        if (networkAutoSwitch) {
            val wifiLatency: Int = doTestLatency(
                "114.114.114.114",
                53,
                NetworkAdapter.wifiNetwork
            )
            wifiLatencyList.add(wifiLatency)
            val cellularLatency: Int = doTestLatency(
                "114.114.114.114",
                53,
                NetworkAdapter.cellularNetwork
            )
            cellularLatencyList.add(cellularLatency)
            Timber.d("wifi latency: $wifiLatency, cellular latency: $cellularLatency")
        }
    }

    private suspend fun doTestLatency(
        pingHost: String,
        pingPort: Int,
        network: Network?,
        systemNetwork: Boolean = false
    ): Int {
        return withTimeoutOrNull(DataStore.pingTimeoutMillis.toLong()) {
            try {
                val socketAddress: Socket = when {
                    network != null -> {
                        network.socketFactory.createSocket()
                    }
                    systemNetwork -> {
                        Socket()
                    }
                    else -> {
                        return@withTimeoutOrNull -1
                    }
                }
                val start = System.currentTimeMillis()
                socketAddress.connect(
                    InetSocketAddress(pingHost, pingPort),
                    DataStore.pingTimeoutMillis
                )
                (System.currentTimeMillis() - start).toInt()
            } catch (_: Exception) {
                -1
            }
        } ?: -1
    }

    var loginAuthToken: String = "1"


}