package com.ccwangluo.accelerator.ui.web

import android.webkit.JavascriptInterface
import androidx.core.content.ContextCompat.checkSelfPermission
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.cc_quickly.utils.XToastUtils
import com.just.agentweb.core.AgentWeb
import com.xuexiang.xpage.base.XPageFragment


/**
 * js注入的方法
 */
class AndroidInterface(val xPageFragment: XPageFragment, val agentWeb: AgentWeb) {

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

    @JavascriptInterface
    fun close() {
        xPageFragment.popToBack()
    }

    @JavascriptInterface
    fun open(pageName: String) {
        xPageFragment.openPage(pageName)
    }

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


    /**
     * 检查权限
     */
    @JavascriptInterface
    fun getPermissionState(key: String, callback: String) {
        xPageFragment.context?.let {
            val hasPermission: Boolean = if (checkSelfPermission(it, key) > 0) true else false
            agentWeb.getJsAccessEntrace()
                .quickCallJs(callback,key, hasPermission.toString())
        }
    }

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

}