package com.adealink.weparty.network

import com.adealink.frame.base.AppBase
import com.adealink.frame.base.IError
import com.adealink.frame.locale.country.getNewCountryCode
import com.adealink.frame.locale.language.languageManager
import com.adealink.frame.network.INetworkConfig
import com.adealink.frame.network.data.C_ERROR_SOCKET_DISCONNECT
import com.adealink.frame.network.data.C_ERROR_SOCKET_MSG_ERROR
import com.adealink.frame.network.data.C_ERROR_SOCKET_MSG_SEND_FAILED
import com.adealink.frame.network.data.C_ERROR_SOCKET_MSG_SEND_TIMEOUT
import com.adealink.frame.network.data.NetworkSocketDisconnectError
import com.adealink.frame.network.data.NetworkSocketMsgError
import com.adealink.frame.network.data.NetworkSocketMsgSendFailedError
import com.adealink.frame.network.data.NetworkSocketMsgSendTimeoutError
import com.adealink.frame.network.stat.WebSocketEvent
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.PackageUtil
import com.adealink.frame.util.getHost
import com.adealink.weparty.App
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.channel.getChannel
import com.adealink.weparty.debug.DebugPrefs
import com.adealink.weparty.error.CommonFunctionBlockError
import com.adealink.weparty.error.CommonHasSensitiveWordError
import com.adealink.weparty.error.CommonIllegalPictureError
import com.adealink.weparty.error.CommonOperationLimitError
import com.adealink.weparty.error.TokenExpireError
import com.adealink.weparty.error.UserBannedError
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.storage.file.FilePath
import com.adealink.frame.util.getNetworkType
import com.adealink.weparty.debug.DebugPrefs.testDeviceId
import com.google.gson.Gson
import okhttp3.Interceptor

class NetworkConfig : INetworkConfig {

//    private val statHttpService by lazy {
//        App.instance.networkService.getReportHttpService(ServerStatHttpService::class.java)
//    }

    override val baseUrl: String
        get() {
            return when {
                AppBase.isRelease -> "https://${getLocalHost()}/"
                else -> DebugPrefs.httpUrl
            }
        }
    override val reportUrl: String = "http://${getLocalHost()}/"

    override val gson: Gson
        get() = com.adealink.frame.data.json.gson
    override val httpAntiBanConfigUrl: String
        get() = ""//"http://49.51.172.109:8080/api/config/getHostEndpointConfig"
    override val githubAntiBanConfigUrl: String
        get() = ""//"https://raw.githubusercontent.com/wenext-09/config/main/yoki/host.json"
    override val hardcodeMainHosts: List<String>
        get() {
            return when {
                AppBase.isRelease -> RELEASE_HOSTS
                else -> listOf(getHost(DebugPrefs.httpUrl))
            }
        }
    override val hardcodeBackupHosts: List<String>
        get() {
            return when {
                AppBase.isRelease -> BACKUP_HOSTS
                else -> listOf()
            }
        }
    override val langCountryCode: String
        get() = languageManager?.getLocaleCountryCode() ?: ""
    override val languageCode: String
        get() = languageManager?.getLanguageCode() ?: ""
    override val channel: String
        get() = "official"//getChannel()
    override val countryCode: String
        get() = getNewCountryCode()
    override val currActivityName: String
        get() = AppUtil.cacheCurrentActivity?.componentName?.className ?: ""
    override val deviceId: String
        get() = if (AppBase.isRelease) {
            App.instance.deviceIdService.getMemOldDeviceId()
        } else {
            testDeviceId.ifEmpty { App.instance.deviceIdService.getMemOldDeviceId() }
        }

    override val newDeviceId: String
        get() = App.instance.deviceIdService.getMemDeviceId()
    override val packageName: String
        get() = PackageUtil.getPackageName()

    // 缓存时间一般不会很长, 一般是1-3分钟. 加入首页, 房间用到的域名即可
    override val preloadDomains: List<String>
        get() = buildList {
            addAll(RELEASE_HOSTS)
            //add(CDN_HOST)
        }

    override val protocolCachePath: String
        get() = FilePath.httpCachePath
    override val protocolCacheSize: Long
        get() = 10 * 1024 * 1024
    override val token: String
        get() = AccountModule.token
    override val uid: String
        get() = AccountModule.uid
    override val userRegion: String
        get() = ""

    override val versionCode: String
        get() = BuildConfig.VERSION_NAME

    override val webCachePath: String
        get() = FilePath.webPath

    override val webCacheSize: Long
        get() = 50 * 1024 * 1024 // 50M

    override val loggedIn: Boolean
        get() = AccountModule.isLogin()
    override val networkType: String
        get() = getNetworkType()
    override val signKey: String
        get() = if (AppBase.isProdEnv) {
            BuildConfig.SIGN_KEY
        } else {
            BuildConfig.SIGN_KEY_DEBUG
        }

    override fun getNetworkInterceptors(): List<Interceptor> {
        return listOf()
    }

    override fun getInterceptors(): List<Interceptor> {
        return listOf()
    }

    override fun getErrorByServerCode(
        code: Int,
        msg: String,
        data: Any?,
        toastSeconds: Int
    ): IError {
        return when (code) {
            C_ERROR_SOCKET_MSG_SEND_TIMEOUT -> NetworkSocketMsgSendTimeoutError()
            C_ERROR_SOCKET_MSG_ERROR -> NetworkSocketMsgError()
            C_ERROR_SOCKET_MSG_SEND_FAILED -> NetworkSocketMsgSendFailedError()
            C_ERROR_SOCKET_DISCONNECT -> NetworkSocketDisconnectError()
            ServerCode.HAS_SENSITIVE_WORD.code -> CommonHasSensitiveWordError()
            ServerCode.ILLEGAL_PICTURE.code -> CommonIllegalPictureError()
            ServerCode.OPERATION_LIMIT.code -> CommonOperationLimitError()
            ServerCode.DEVICE_OPERATION_LIMIT.code -> CommonOperationLimitError()
            ServerCode.TOKEN_EXPIRE.code -> TokenExpireError()
            ServerCode.USER_BANNED.code -> UserBannedError(data)
            ServerCode.FUNCTION_BLOCK.code -> CommonFunctionBlockError(data, msg)
            else -> IError(msg, code, data = data)
        }
    }

    override fun getExtraHeaders(): Map<String, String>? {
        return null
    }

    override fun onNetworkResponseError(code: Int, msg: String?, data: Any?) {
        when (code) {
            ServerCode.TOKEN_EXPIRE.code -> {
                AccountModule.onTokenExpire()
            }

            ServerCode.USER_BANNED.code -> {
                // TODO: 用户被封禁 
//                AccountModule.onUserBanned(null)
            }

            else -> {
                //ntd.
            }
        }
    }

    override fun onStartCoreReq() {
        App.instance.downloadService.stopLowPriorityTask()
    }

    override fun onEndCoreReq() {
        App.instance.downloadService.startLowPriorityTask()
    }

}