package com.gamedog.vididin.features.game

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.view.LayoutInflater
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.ama.core.architecture.BaseApp
import com.ama.core.architecture.appBase.AppViewsActivity
import com.ama.core.architecture.util.AndroidUtil
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.viddin.videos.free.R
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.gamedog.vididin.main.MainUiState as UiState
import com.gamedog.vididin.main.MainViewModel as ViewModel
import com.viddin.videos.free.databinding.ActivityGameBinding as ViewBinding


@AndroidEntryPoint
class GameCenterActivity : AppViewsActivity<ViewBinding, UiState, ViewModel>(), OnTabStyleListener {

    override val mViewModel: ViewModel by viewModels()
    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)
    override var mEnableBannerAd = false

    @SuppressLint("SetJavaScriptEnabled")
    override fun ViewBinding.initViews() {


        with(binding) {
            titlebar.setBackIconColor(R.color.black)
            titlebar.setTitleText(R.string.game_center, R.color.black)


            onBackPressedDispatcher.addCallback(this@GameCenterActivity) {
                if (webView.canGoBack()) {
                    webView.goBack()
                } else {
                    finish()
                }
            }

            with(webView) {
                settings.javaScriptEnabled = true
                webView.addJavascriptInterface(WebAppInterface(this@GameCenterActivity, webView), "com.viddin.videos.free")

                webViewClient = object : WebViewClient() {
                    override fun shouldOverrideUrlLoading(
                        view: WebView?,
                        request: WebResourceRequest
                    ): Boolean {
                        request.url?.let { url ->
                            if (!request.url.toString().startsWith("intent")) {
                                view?.loadUrl(url.toString())
                                return true
                            } else {
                                try {
                                    handleIntentUrl(url.toString())
                                    return true
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                        return false
                    }


                    @Deprecated("For API level < 24")
                    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                        if (!url.isNullOrBlank() && !url.startsWith("intent")) {
                            view?.loadUrl(url)
                            return true
                        }
                        return false
                    }
                }

            }

            loadGameCenterWeb()
        }


        StatisticUtil.reportEvents(StatisticUtil.KEY_H5_Show)
    }



    private fun loadGameCenterWeb() {
        var gaid: String? = ""

        showLoading(false)
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                gaid = AndroidUtil.getGaid()
            }

            if (!gaid.isNullOrBlank()) {
                binding.webView.loadUrl(String.format(VidiConst.URL_GAME, gaid))
                hideLoading()
            } else {
                hideLoading()
            }
        }

    }


    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(contentRoot)
    }

    override fun ViewBinding.initListeners() {
        //TODO("Not yet implemented")
    }

    override fun ViewBinding.initObservers() {
        //TODO("Not yet implemented")
    }

    override fun ViewBinding.onUiStateCollect(uiState: UiState) {
        //TODO("Not yet implemented")
    }

    override fun onTabIsDarkFont(isDarkFont: Boolean) {
        //TODO("Not yet implemented")
    }

    private fun handleIntentUrl(url: String) {
        var intent: Intent? = null
        if (url.startsWith("intent")) {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
        }

        if (intent != null) {
            if (isHw()) {
                intent.setPackage(getDefaultBrowser())
            }
            intent.addCategory(Intent.CATEGORY_BROWSABLE)
            intent.setComponent(null)
            intent.setFlags(FLAG_ACTIVITY_NEW_TASK)
        }
        this.startActivity(intent)
    }

    fun isHw(): Boolean {
        return "huawei".equals(Build.MANUFACTURER, ignoreCase = true)
    }

    fun getDefaultBrowser(): String? {
        var packageName: String? = null
        var systemApp: String? = null
        var userApp: String? = null
        val userAppList: MutableList<String?> = ArrayList<String?>()
        val context: Context = BaseApp.appContext()
        val browserIntent = Intent("android.intent.action.VIEW", Uri.parse("https://"))
        val resolveInfo = context.getPackageManager()
            .resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)
        if (resolveInfo != null && resolveInfo.activityInfo != null) {
            packageName = resolveInfo.activityInfo.packageName
        }
        if (packageName == null || packageName == "android") {
            val lists = context.getPackageManager().queryIntentActivities(browserIntent, 0)
            for (app in lists) {
                if ((app.activityInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0) {
                    systemApp = app.activityInfo.packageName
                } else {
                    userApp = app.activityInfo.packageName
                    userAppList.add(userApp)
                }
            }
            if (userAppList.contains("com.android.chrome")) {
                packageName = "com.android.chrome"
            } else {
                if (systemApp != null) {
                    packageName = systemApp
                }
                if (userApp != null) {
                    packageName = userApp
                }
            }
        }
        return packageName
    }


    companion object {
        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, GameCenterActivity::class.java))
        }
    }

}


class WebAppInterface(private val context: Activity, private val webView: WebView) {
    @JavascriptInterface
    fun openBrowser(url: String) {
        try {
            var intent: Intent? = null
            if (url.startsWith("intent")) {
                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
            } else {
                intent = Intent("android.intent.action.VIEW", Uri.parse(url))
            }
            if (intent != null) {
                if (isHw()) {
                    intent.setPackage(getDefaultBrowser())
                }
                intent.addCategory(Intent.CATEGORY_BROWSABLE)
                intent.setComponent(null)
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //点击互动广告关闭按钮时调用该方法。
    @JavascriptInterface
    fun close() {
        //TODO  close the ad page or activity.
    }

    //接入Gspace-Fully广告时需实现此方法。该方法用于打开新的Webview页面。
    @JavascriptInterface
    fun openWebview(url: String?) {
        //TODO  open a new page to display landingpage.
        //TODO 使用展示GSpace的Activity新实例打开当前url.
    }

    fun isHw(): Boolean {
        return "huawei".equals(Build.MANUFACTURER, ignoreCase = true)
    }

    fun getDefaultBrowser(): String? {
        var packageName: String? = null
        var systemApp: String? = null
        var userApp: String? = null
        val userAppList: MutableList<String?> = ArrayList<String?>()
        val context: Context = BaseApp.appContext()
        val browserIntent = Intent("android.intent.action.VIEW", Uri.parse("https://"))
        val resolveInfo = context.getPackageManager()
            .resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)
        if (resolveInfo != null && resolveInfo.activityInfo != null) {
            packageName = resolveInfo.activityInfo.packageName
        }
        if (packageName == null || packageName == "android") {
            val lists = context.getPackageManager().queryIntentActivities(browserIntent, 0)
            for (app in lists) {
                if ((app.activityInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0) {
                    systemApp = app.activityInfo.packageName
                } else {
                    userApp = app.activityInfo.packageName
                    userAppList.add(userApp)
                }
            }
            if (userAppList.contains("com.android.chrome")) {
                packageName = "com.android.chrome"
            } else {
                if (systemApp != null) {
                    packageName = systemApp
                }
                if (userApp != null) {
                    packageName = userApp
                }
            }
        }
        return packageName
    }
}
