package com.adealink.weparty.image

import android.content.Context
import com.adealink.frame.data.json.froJsonErrorNull
import com.adealink.frame.image.config.IImageConfig
import com.adealink.frame.image.constant.ImageFetchResultData
import com.adealink.frame.image.constant.TAG_IMAGE_CONFIG
import com.adealink.frame.log.Log
import com.adealink.frame.network.stat.NetMonitorStatEvent
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.App
import com.adealink.weparty.config.GlobalConfigType
import com.adealink.weparty.config.IGlobalConfigListener
import com.adealink.weparty.image.datasource.local.ImageLocalService
import okhttp3.OkHttpClient

class ImageConfig : IImageConfig, IGlobalConfigListener {

    companion object {
        private const val COS_RESIZE_QUERY = "imageMogr2/thumbnail/\${width}x\${height}>"
        private const val OSS_RESIZE_QUERY =
            "x-oss-process=image/resize,w_\${width},h_\${height},m_mfit"
        private const val ALICDN_RESIZE_QUERY = "image_process=resize,fw_\${width},fh_\${height}"
    }

    override val context: Context
        get() = App.instance
    override val hostToResizeQuery = hashMapOf<String, String>()
    override val imageHttpClient: OkHttpClient
        get() = App.instance.networkService.imageHttpClient

    override fun replaceUrlHost(oldUrl: String): String {
        return App.instance.networkService.replaceUrlHost(oldUrl)
    }

    override fun report(data: ImageFetchResultData) {
        val (url, host, size, duration, protocol, tlsVersion, awsXAmzCfId) = data
        NetMonitorStatEvent(NetMonitorStatEvent.Action.TRAFFIC)
            .apply {
                uri to url
                this.host to host
                amount to size
                this.duration to duration
                this.protocol to protocol
                this.tlsVersion to tlsVersion
                xAmzCfId to awsXAmzCfId
            }
            .send()
    }

    //TODO 全量CDN之后以下部分需要被移除，减少判断性能消耗
    private val aliOssHosts = emptySet<String>(
//        "yoki-resource-cf.wenext.media",
//        "yoki-user-cf.wenext.media",
//        "wenext-yoki-user.oss-ap-southeast-1.aliyuncs.com",
//
//        "wenext-lama.oss-ap-southeast-1.aliyuncs.com",
//        "wenext-lama.oss-accelerate.aliyuncs.com",
//        "wenext-lama.oss-accelerate-overseas.aliyuncs.com",
//        "wyak.oss-ap-southeast-1.aliyuncs.com",
//        "wyak.oss-accelerate.aliyuncs.com",
//        "wyak.oss-accelerate-overseas.aliyuncs.com",
//
//        "wenext-yoki.oss-ap-southeast-1.aliyuncs.com",
//        "wenext-yoki.oss-accelerate.aliyuncs.com",
//        "wenext-yoki.oss-accelerate-overseas.aliyuncs.com",
    )

    //TODO 全量CDN之后以下部分需要被移除，减少判断性能消耗
    private val qCloudCosHosts = hashSetOf(
        "lanu-public-test-1377959011.cos.ap-guangzhou.myqcloud.com",
//        "wayak-system-1314119829.cos.eu-frankfurt.myqcloud.com",
//        "wayak-system-1314119829.cos.accelerate.myqcloud.com",
//        "weparty-user-1314119829.cos.eu-frankfurt.myqcloud.com",
//        "weparty-user-1314119829.cos.accelerate.myqcloud.com"
    )

    //阿里云cdn回源到阿里oss
    private val aliCdn2AliOssHosts = hashSetOf(
        "cdn.wenext.love",
    )

    //腾讯云cdn回源到阿里oss
    private val qCloudCdn2AliOssHosts = emptyList<String>(
//        "public.gami.vip",
//        "lama.wenext.media",
//        "wyak-user.wenext.media"
    )

    //腾讯云cdn回源到腾讯云cos
    private val qCloudCdn2QCloudCosHosts = hashSetOf(
        "public.gami.vip",
//        "wayak-resource.wenext.media",
//        "weparty-user.wenext.media"
    )

    init {
        aliOssHosts.forEach {
            hostToResizeQuery[it] = OSS_RESIZE_QUERY
        }
        qCloudCosHosts.forEach {
            hostToResizeQuery[it] = COS_RESIZE_QUERY
        }
        aliCdn2AliOssHosts.forEach {
            hostToResizeQuery[it] = ALICDN_RESIZE_QUERY
        }
        qCloudCdn2AliOssHosts.forEach {
            hostToResizeQuery[it] = OSS_RESIZE_QUERY
        }
        qCloudCdn2QCloudCosHosts.forEach {
            hostToResizeQuery[it] = COS_RESIZE_QUERY
        }
        // TODO: CDN
//        globalConfigManager.addListener(GlobalConfigType.GLOBAL_CDN_RESIZE, this)
//        val newConfig = globalConfigManager.getConfig(GlobalConfigType.GLOBAL_CDN_RESIZE)
//        if (newConfig != null) {
//            onNewConfigGet(newConfig)
//        } else {
//            val localConfigJson = ImageLocalService.resizeQueryConfig
//            if (localConfigJson.isNotEmpty()) {
//                handleResizeQueryConfig(localConfigJson)
//            }
//        }
    }

    override fun onConfigGet(configType: GlobalConfigType, config: List<String>) {
        // TODO: CDN
//        if (configType != GlobalConfigType.GLOBAL_CDN_RESIZE) {
//            return
//        }
//
//        onNewConfigGet(config)
    }

    private fun onNewConfigGet(config: List<String>) {
        val resizeQueryConfig = config.getOrNull(0)
        if (resizeQueryConfig.isNullOrEmpty()) {
            return
        }

        Log.i(TAG_IMAGE_CONFIG, "onNewConfigGet, resizeQueryConfig:$resizeQueryConfig")
        ImageLocalService.resizeQueryConfig = resizeQueryConfig
        handleResizeQueryConfig(resizeQueryConfig)
    }

    private fun handleResizeQueryConfig(configJson: String) {
        val configs = froJsonErrorNull<Map<String, String>>(configJson) ?: return
        Log.i(TAG_IMAGE_CONFIG, "handleResizeQueryConfig, configs:$configs")
        runOnUiThread {
            hostToResizeQuery.putAll(configs)
        }
    }


}