package com.gh.gamecenter.common.utils

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.therouter.TheRouter
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.provider.IAppProvider
import com.gh.gamecenter.core.provider.IBuildConfigProvider
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SPUtils

object EnvHelper {

    // API 环境是否为测试环境
    @JvmStatic
    val isDevEnv: Boolean by lazy {
        SPUtils.getBoolean(Constants.SP_IS_DEV_ENV, false)
    }

    @JvmStatic
    val isGATApp: Boolean by lazy {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        buildConfig?.isGATApp() ?: false
    }

    private const val DEFAULT_LOG_PRODUCER_PROJECT = "ghzs"

    @JvmStatic
    val logProducerProject: String by lazy {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        buildConfig?.getLogProducerProject() ?: DEFAULT_LOG_PRODUCER_PROJECT
    }

    @JvmStatic
    fun getHost(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return if (!PackageFlavorHelper.IS_TEST_FLAVOR) {
            buildConfig?.getApiHost() ?: "https://and-api.ghzs6.com/v5d5d0/"
        } else {
            if (isDevEnv) {
                buildConfig?.getDevApiHost() ?: ""
            } else {
                buildConfig?.getApiHost() ?: ""
            }
        }
    }

    @JvmStatic
    fun getVHost(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return if (!PackageFlavorHelper.IS_TEST_FLAVOR) {
            buildConfig?.getVApiHost() ?: "https://app-api.796697.com"
        } else {
            if (isDevEnv) {
                buildConfig?.getVDevApiHost() ?: ""
            } else {
                buildConfig?.getVApiHost() ?: ""
            }
        }
    }

    @JvmStatic
    fun getNewHost(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return if (!PackageFlavorHelper.IS_TEST_FLAVOR) {
            buildConfig?.getNewApiHost() ?: "https://app-api.ghzs6.com/"
        } else {
            if (isDevEnv) {
                buildConfig?.getNewDevApiHost() ?: ""
            } else {
                buildConfig?.getNewApiHost() ?: ""
            }
        }
    }

    @JvmStatic
    fun getWGameCPMHost(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return buildConfig?.getWGameCPMApiHost() ?: ""
    }

    @JvmStatic
    fun getDspHost(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return buildConfig?.getDspApiHost() ?: ""
    }

    @JvmStatic
    fun getWGameCPMBusiAppId(): String {
        val buildConfig = TheRouter.get(IBuildConfigProvider::class.java)
        return buildConfig?.getWGameCPMBusiAppId() ?: ""
    }

    fun showChangeChannelDialog(context: Context, restartAfterChanges: Boolean = false) {
        val appProvider = TheRouter.get(IAppProvider::class.java)
        val layout = LinearLayout(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            gravity = Gravity.CENTER
            orientation = LinearLayout.VERTICAL
            setPadding(DisplayUtils.dip2px(16F), DisplayUtils.dip2px(16F), DisplayUtils.dip2px(16F), 0)
        }

        val editText = EditText(context)
        var channel = SPUtils.getString(Constants.SP_TEST_FLAVOR_CHANNEL)
        if (TextUtils.isEmpty(channel)) {
            channel = appProvider?.getChannel() ?: ""
            SPUtils.setString(Constants.SP_TEST_FLAVOR_CHANNEL, channel)
        }
        editText.setText(channel, TextView.BufferType.EDITABLE)
        editText.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        layout.addView(editText)

        // 推荐渠道
        val channelContainer = LinearLayout(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            orientation = LinearLayout.HORIZONTAL
        }
        channelContainer.addView(
            TextView(context).apply { text = "推荐渠道：" }
        )
        val channelList = listOf("GH_REFRESH", "GH_TEST3", "GH_206")
        channelList.forEach { title ->
            channelContainer.addView(
                TextView(context).apply {
                    text = title
                    setTextColor(ContextCompat.getColor(context, R.color.text_theme))
                    setOnClickListener {
                        editText.setText(title, TextView.BufferType.EDITABLE)
                    }
                },
                LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    leftMargin = 10F.dip2px()
                }
            )
        }
        layout.addView(channelContainer)

        val inputDialog: AlertDialog.Builder = AlertDialog.Builder(context)
        inputDialog.setTitle("请输入渠道：").setView(layout)
        inputDialog.setPositiveButton(context.getString(R.string.confirm)) { _, _ ->
            val flavorChannel = SPUtils.getString(Constants.SP_TEST_FLAVOR_CHANNEL)
            if (!TextUtils.isEmpty(editText.text) && editText.text.toString() != flavorChannel) {
                appProvider?.setChannel(editText.text.toString())
                SPUtils.setString(Constants.SP_TEST_FLAVOR_CHANNEL, editText.text.toString())
                if (restartAfterChanges) {
                    AppExecutor.uiExecutor.executeWithDelay({
                        val pm = context.packageManager
                        val intent = pm.getLaunchIntentForPackage(context.packageName)
                        val mainIntent = Intent.makeRestartActivityTask(intent!!.component)
                        context.startActivity(mainIntent)
                        Runtime.getRuntime().exit(0)
                    }, 300L)
                }
            }
        }.show()
    }

    fun showChangeIpDialog(context: Context) {
        val layout = LinearLayout(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            gravity = Gravity.CENTER
            orientation = LinearLayout.VERTICAL
            setPadding(
                DisplayUtils.dip2px(16F),
                DisplayUtils.dip2px(16F),
                DisplayUtils.dip2px(16F),
                0
            )
        }

        val editText = EditText(context)
        val ip = SPUtils.getString(Constants.SP_TEST_FLAVOR_IP)
        if (ip.isNotEmpty()) {
            editText.setText(ip, TextView.BufferType.EDITABLE)
        } else {
            editText.setHintTextColor(R.color.hint.toColor(context))
            editText.setHint("请输入 IP，格式是 x.x.x.x ")
        }
        editText.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        layout.addView(editText)

        // 预设 IP
        val ipContainer = LinearLayout(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            orientation = LinearLayout.HORIZONTAL
        }
        ipContainer.addView(
            TextView(context).apply { text = "预设 IP：" }
        )

        val ipHashMap = hashMapOf<String, String>()

        ipHashMap["重置"] = ""
        ipHashMap["黑龙江"] = "117.179.243.51"
        ipHashMap["浙江"] = "183.128.0.0"
        ipHashMap["河北"] = "120.0.0.0"
        ipHashMap["北京"] = "110.96.0.0"
        ipHashMap["上海"] = "180.160.0.0"

        ipHashMap.forEach { pair ->
            ipContainer.addView(
                TextView(context).apply {
                    text = pair.key
                    setTextColor(ContextCompat.getColor(context, R.color.text_theme))
                    setOnClickListener {
                        editText.setText(pair.value, TextView.BufferType.EDITABLE)
                    }
                },
                LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    leftMargin = 10F.dip2px()
                }
            )
        }
        layout.addView(ipContainer)

        val inputDialog: AlertDialog.Builder = AlertDialog.Builder(context)
        inputDialog.setTitle("请输入 IP：").setView(layout)
        inputDialog.setNegativeButton("网页自选") { _, _ ->
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = android.net.Uri.parse("http://ips.chacuo.net/")
            context.startActivity(intent)
        }
        inputDialog.setPositiveButton(context.getString(R.string.confirm)) { _, _ ->
            val defaultValue = SPUtils.getString(Constants.SP_TEST_FLAVOR_IP)
            if (editText.text.toString() != defaultValue) {
                SPUtils.setString(Constants.SP_TEST_FLAVOR_IP, editText.text.toString())
                AppExecutor.uiExecutor.executeWithDelay({
                    val pm = context.packageManager
                    val intent = pm.getLaunchIntentForPackage(context.packageName)
                    val mainIntent = Intent.makeRestartActivityTask(intent!!.component)
                    context.startActivity(mainIntent)
                    Runtime.getRuntime().exit(0)
                }, 300L)
            }
        }.show()
    }
}