package com.ccwangluo.accelerator.ui.web

import android.os.Bundle
import android.webkit.JavascriptInterface
import com.ccwangluo.accelerator.utils.LoginUtils
import com.github.shadowsocks.http.HttpConfig
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.ccwangluo.cc_quickly.utils.XToastUtils
import com.just.agentweb.core.AgentWeb
import com.xuexiang.xutil.app.AppUtils
import com.xuexiang.xutil.system.PermissionUtils
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import com.ccwangluo.accelerator.utils.SysUtils
import com.github.shadowsocks.bg.AuthManager
import com.xuexiang.xpage.base.XPageActivity


/**
 * js注入的方法
 */
class AndroidActivityInterface(val xPageActivity: XPageActivity, val agentWeb: AgentWeb) {

    @JavascriptInterface
    fun callAndroid(msg: String) {
        XToastUtils.toast("这是Js调用Android的方法，内容:$msg")
    }

    @JavascriptInterface
    fun close() {
        xPageActivity.popPage()
    }

    @JavascriptInterface
    fun openNative(pageName: String) {
        xPageActivity.openPage(pageName)
    }

    @JavascriptInterface
    fun openWebview(url: String) {
        LoginUtils.token?.let {
            val intent = Intent(xPageActivity,BlankActivity::class.java)
            intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL + url)
            xPageActivity?.startActivity(intent)
        } ?: let {
            xPageActivity?.let { it1 ->
                LoginUtils.login(it1) {
                    LoginUtils.token?.let {
                        agentWeb.getJsAccessEntrace()
                            .quickCallJs("userToken", it)
                    }
                }
            }
        }
    }


    /**
     * 跳转协议
     */
    @JavascriptInterface
    fun openWebviewByWholeUrl(url: String) {
        val intent = Intent(xPageActivity,BlankActivity::class.java)
        if(url.startsWith("http:")||url.startsWith("https:")){
            intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY,  url)
        }else{
            intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY,  HttpConfig.HTML_HOST_PRIVACY+url)
        }
        xPageActivity?.startActivity(intent)
    }

    //打开系统设置
    @JavascriptInterface
    fun openSysSetting() {
        xPageActivity.startActivity( Intent(Settings.ACTION_SETTINGS));
    }

    @JavascriptInterface
    fun openAsideWebview(url: String) {
        val intent = Intent(xPageActivity,BlankActivity::class.java)
        intent.putExtra(CommonWebViewFragment.WEBVIEW_URL_KEY,  url)
        xPageActivity?.startActivity(intent)
    }

    @JavascriptInterface
    fun login(callback: String) {
        xPageActivity?.let {
            LoginUtils.login(it, {
                if (it) {
                    agentWeb.getJsAccessEntrace()
                        .quickCallJs(callback, LoginUtils.token)
                }
            })
        }
    }

    /**
     * 打开外部系统浏览器
     */
    @JavascriptInterface
    fun goSysBrowser(url: String?) {
        val uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        xPageActivity.startActivity(intent)
    }

    /**
     * 智能极限加速
     */
    @JavascriptInterface
    fun setSmartAccOpen(isopen: Boolean) {
        AuthManager.isSmartAccOpen = isopen
    }

    /**
     * 智能极限加速
     */
    @JavascriptInterface
    fun getSmartAccStatus(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(callback, AuthManager.isSmartAccOpen.toString())
    }

    /**
     * 清除token
     */
    @JavascriptInterface
    fun clearToken() {
        LoginUtils.clearToken()
    }


    /**
     * 检查权限
     */
    @JavascriptInterface
    fun getPermissionState(key: String, callback: String) {
        xPageActivity?.let {
            val hasPermission: Boolean = PermissionUtils.isGranted(key)
            agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, key, hasPermission.toString())
        }
    }

    /**
     * 申请权限
     */
    @JavascriptInterface
    fun requirePermissionState(key: String, callback: String) {
        xPageActivity?.let {
            PermissionUtils.permission(key).rationale({
                PermissionUtils.openAppSettings()
            }).callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: MutableList<String>?) {
                    permissionsGranted?.forEach {
                        if (it.equals(key)) {
                            agentWeb.getJsAccessEntrace()
                                .quickCallJs(callback, key, "true")
                        }
                    }

                }

                override fun onDenied(
                    permissionsDeniedForever: MutableList<String>?,
                    permissionsDenied: MutableList<String>?
                ) {
                    permissionsDenied?.forEach {
                        if (it.equals(key)) {
                            agentWeb.getJsAccessEntrace()
                                .quickCallJs(callback, key, "false")
                        }
                    }
                    permissionsDeniedForever?.forEach {
                        if (it.equals(key)) {
                            PermissionUtils.openAppSettings()
                        }
                    }

                }

            }).request()
        }
    }

    /**
     * 检查安装包
     */
    @JavascriptInterface
    fun getPackageState(packageName: String, callback: String) {
        xPageActivity?.let {
            val packageInstall = SysUtils.isPackageInstall(it, packageName)
            agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, packageName, packageInstall.toString())
        }
    }

    /**
     * 卸载程序
     */
    @JavascriptInterface
    fun uninstallPackge(pageName: String) {
        AppUtils.uninstallApp(pageName)
    }

    /**
     * 安装
     */
    @JavascriptInterface
    fun installPackge(pageName: String) {
//        AppUtils.installApp(pageName)
    }

    /**
     * 版本号
     */
    @JavascriptInterface
    fun getVersion(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(
                callback,
                AppUtils.getAppVersionName(),
                AppUtils.getAppVersionCode().toString()
            )
    }

    /****************
     *
     * 发起添加群流程。
     * 调用 joinQQGroup(09Gg-vMtnaIfgr-slk1pOkjVIFmjI79U)
     */
    @JavascriptInterface
    fun joinQQGroup() {
        xPageActivity?.let {
            SysUtils.joinQQGroup(it)
        }

    }

    @JavascriptInterface
    fun getSystemVersion(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(
                callback,
                android.os.Build.VERSION.RELEASE,
                SysUtils.getDpi(xPageActivity).toString(),android.os.Build.VERSION.SDK_INT.toString()
            )
    }

    /**
     * 获取android dpi
     */
    @JavascriptInterface
    fun getDpi(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(callback, SysUtils.getDpi(xPageActivity).toString())
    }

    @JavascriptInterface
    fun closeApp() {
        LoginUtils.clearToken()
        System.exit(0)
    }

}