package com.gh.ad

import com.gh.download.simple.DownloadMessageHandler
import com.gh.download.simple.SimpleDownloadDatabase
import com.gh.download.simple.SimpleDownloadManager
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.PluginRedirectHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.lg.download.DownloadError
import com.lg.download.DownloadStatus
import com.lg.download.httpclient.DefaultHttpClient
import com.lg.download.listener.InnerDownloadListener
import com.lg.ndownload.DownloadConfig
import com.lg.ndownload.DownloadConfigBuilder
import com.lg.ndownload.DownloadIoExecutor
import com.lightgame.utils.Utils
import java.lang.Exception
import java.net.URLConnection

object AdPluginDownloadHelper : InnerDownloadListener {

    private const val CSJ_FILE_NAME = "1832823466"
    private const val GDT_FILE_NAME = "gdt_plugin/gdtadv2.jar"

    private const val CSJ_PLUGIN_URL = "https://and-static.ghzs66.com/android/static/1832823466"
    private const val GDT_PLUGIN_URL = "https://and-static.ghzs66.com/android/static/gdtadv2.jar"

    private var csjDownloadedCallback: (() -> Unit)? = null

    /**
     * 是否已经下载了广告插件
     */
    fun isCsjPluginDownloaded(): Boolean {
        return SPUtils.getBoolean(CSJ_FILE_NAME, false)
    }

    /**
     * 下载广告插件并初始化 （初始化限定穿山甲）
     */
    fun downloadPluginIfNeeded(isCsj: Boolean = false, isGdt: Boolean = false, csjCallback: (() -> Unit)? = null) {
        val isCsjPluginDownloaded = SPUtils.getBoolean(CSJ_FILE_NAME, false)
        val isGdtPluginDownloaded = SPUtils.getBoolean(GDT_FILE_NAME, false)

        if (isCsj && isCsjPluginDownloaded) {
            csjCallback?.invoke()
            return
        }

        if (isGdt && isGdtPluginDownloaded) {
            return
        }

        runOnIoThread {
            csjDownloadedCallback = csjCallback

            DownloadMessageHandler.init(SimpleDownloadDatabase.instance.downloadDao())

            if (!isCsjPluginDownloaded && isCsj) {
                val csjPluginConfig = DownloadConfigBuilder()
                    .setUniqueId(CSJ_FILE_NAME)
                    .setUrl(CSJ_PLUGIN_URL)
                    .setFileName(CSJ_FILE_NAME)
                    .setHttpClient(DefaultHttpClient())
                    .setDownloadThreadSize(2)
                    .setPathToStore(PluginRedirectHelper.getAssetDir())
                    .setDownloadExecutor(DownloadIoExecutor.getInstance())
                    .setDownloadListener(this).build()

                SimpleDownloadManager.download(csjPluginConfig)
            }

            if (!isGdtPluginDownloaded && isGdt) {
                val gdtPluginConfig = DownloadConfigBuilder()
                    .setUniqueId(GDT_FILE_NAME)
                    .setUrl(GDT_PLUGIN_URL)
                    .setFileName(GDT_FILE_NAME)
                    .setHttpClient(DefaultHttpClient())
                    .setDownloadThreadSize(2)
                    .setPathToStore(PluginRedirectHelper.getAssetDir())
                    .setDownloadExecutor(DownloadIoExecutor.getInstance())
                    .setDownloadListener(this).build()

                SimpleDownloadManager.download(gdtPluginConfig)
            }
        }
    }

    override fun onError(id: String?, error: DownloadError?, exception: Exception?) {
        Utils.log("下载广告插件失败 $id")
        id?.let {
            if (it == CSJ_FILE_NAME) {
                csjDownloadedCallback = null
            }
            SimpleDownloadManager.cancel(it)
        }
    }

    override fun onProgress(id: String?, progress: Float) {
        Utils.log("下载广告插件进度 $id $progress")
    }

    override fun onProgressWithoutThrottle(id: String?, progress: Float) {
        // do nothing
    }

    override fun onSizeReceived(id: String?, fileSize: Long) {
        // do nothing
    }

    override fun onReadyToDownload(id: String?, actualThreadSize: Int) {
        // do nothing
    }

    override fun onStatusChanged(id: String?, status: DownloadStatus?) {
        // do nothing
    }

    override fun onDownloadComplete(id: String?, elapsedTime: Long) {
        id?.let {
            // id 即为插件名
            SPUtils.setBoolean(it, true)
            if (it == CSJ_FILE_NAME) {
                csjDownloadedCallback?.invoke()
                csjDownloadedCallback = null
            }
        }
    }

    override fun onSpeedChanged(id: String?, speed: Float) {
        // do nothing
    }

    override fun onRedirectingUrl(
        id: String?,
        connection: URLConnection?,
        config: DownloadConfig?
    ) {
        // do nothing
    }

    override fun onRedirectedUrl(
        id: String?,
        connection: URLConnection?,
        redirectedUrl: String?
    ) {
        // do nothing
    }

}