package cn.yyxx.eyuancomm.impl.channel.huawei

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import cn.yyxx.eyuancomm.base.entity.ResultInfo
import cn.yyxx.eyuancomm.base.entity.SdkChargeInfo
import cn.yyxx.eyuancomm.base.internal.feature.IApplication
import cn.yyxx.eyuancomm.base.internal.feature.IFeature
import cn.yyxx.eyuancomm.base.internal.feature.ILifeCycle
import cn.yyxx.eyuancomm.base.internal.feature.IOrder
import cn.yyxx.eyuancomm.base.ui.dialog.ScaleLoadingDialog
import cn.yyxx.eyuancomm.base.utils.Logger
import com.huawei.agconnect.AGCRoutePolicy
import com.huawei.agconnect.AGConnectInstance
import com.huawei.agconnect.AGConnectOptionsBuilder
import com.huawei.agconnect.api.AGConnectApi
import com.huawei.agconnect.auth.AGConnectAuth
import com.huawei.agconnect.auth.AGConnectAuthCredential
import com.huawei.hms.analytics.HiAnalytics
import com.huawei.hms.analytics.HiAnalyticsInstance
import com.huawei.hms.analytics.HiAnalyticsTools
import com.huawei.hms.analytics.type.HAEventType
import com.huawei.hms.analytics.type.HAParamType
import com.huawei.hms.api.HuaweiMobileServicesUtil
import com.huawei.hms.common.ApiException
import com.huawei.hms.jos.AppParams
import com.huawei.hms.jos.JosApps
import com.huawei.hms.jos.JosStatusCodes
import com.huawei.hms.jos.games.Games
import com.huawei.hms.jos.games.GamesStatusCodes
import com.huawei.hms.jos.games.buoy.BuoyClient
import com.huawei.hms.support.account.request.AccountAuthParams
import com.huawei.hms.utils.ResourceLoaderUtil
import org.json.JSONObject


/**
 * @author #Suyghur.
 * Created on 2022/01/26
 */
class ChannelSdkHuawei : IFeature, IApplication, ILifeCycle,IOrder {

    private var loginDialog: HuaweiLoginDialog? = null
    private var loadingDialog: ScaleLoadingDialog? = null
    private lateinit var loginCallback: (Int, String) -> Unit
    private lateinit var analytics: HiAnalyticsInstance

    private var buoyClient: BuoyClient? = null

    override fun attachBaseContext(application: Application, context: Context) {

    }

    override fun initApplication(application: Application) {
        HuaweiMobileServicesUtil.setApplication(application)
        // 创建AGConnectOptionsBuilder对象
        val builder = AGConnectOptionsBuilder()
        // 设置数据处理位置，比如将默认数据处理位置从CHINA修改为GERMANY
        builder.routePolicy = AGCRoutePolicy.SINGAPORE
        builder.inputStream = application.assets.open("agconnect-services.json")
        // 初始化AGC框架
        AGConnectInstance.initialize(application, builder)
        HiAnalyticsTools.enableLog()
        analytics = HiAnalytics.getInstance(application)
    }

    override fun initialize(activity: Activity, isLandscape: Boolean, callback: (Int, String) -> Unit) {
        val params = AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM_GAME
        val appClient = JosApps.getJosAppsClient(activity)
        ResourceLoaderUtil.setmContext(activity)
        val initTask = appClient.init(AppParams(params) {
            // 该回调会在如下两种情况下返回:
            // 1.未成年人实名帐号在白天登录游戏，华为会弹框提示玩家不允许游戏，玩家点击“确定”，华为返回回调
            // 2.未成年实名帐号在国家允许的时间登录游戏，到晚上9点，华为会弹框提示玩家已到时间，玩家点击“知道了”，华为返回回调
            // 您可在此处实现游戏防沉迷功能，如保存游戏、调用帐号退出接口或直接游戏进程退出(如System.exit(0))
        })
        initTask.addOnSuccessListener {
            //游戏初始化成功后需要调用一次浮标显示接口
            // showFloatWindowNewWay();
            // 必须在init成功后，才可以实现登录功能
            // signIn();
            Logger.d("Sdk init on success")

            AGConnectApi.getInstance().activityLifecycle().onCreate(activity)

            buoyClient = Games.getBuoyClient(activity)

            AGConnectAuth.getInstance().addTokenListener {
                if (TextUtils.isEmpty(it.token)) {
                    return@addTokenListener
                }
                val jsonObject = JSONObject()
                jsonObject.put("access_token", it.token)
                loginCallback(0, jsonObject.toString())
            }
            callback(0, "Sdk初始化成功")
        }.addOnFailureListener { e ->
            Logger.d("Sdk init on failure")
            if (e is ApiException) {
                Logger.d("Sdk init on failure, code: ${e.statusCode}, msg: ${e.localizedMessage}")
                val statusCode = e.statusCode
                if (statusCode == JosStatusCodes.JOS_PRIVACY_PROTOCOL_REJECTED) {
                    // 错误码为7401时表示用户未同意华为联运隐私协议
                    // 此处您需禁止玩家进入游戏
                    Logger.e("has reject the protocol")
                } else if (statusCode == GamesStatusCodes.GAME_STATE_NETWORK_ERROR) {
                    // 错误码7002表示网络异常
                    // 此处您可提示玩家检查网络，请不要重复调用init接口，否则断网情况下可能会造成手机高耗电。
                    Logger.e("Network error")
                } else {
                    // 在此处实现其他错误码的处理
                }
            }
        }
    }

    override fun login(activity: Activity, callback: (Int, String) -> Unit) {
        loginCallback = callback
        AGConnectAuth.getInstance().signOut()
        loginDialog?.apply {
            dismiss()
            loginDialog = null
        }
        loginDialog = HuaweiLoginDialog(activity)
        loginDialog?.apply {
            ivHw.setOnClickListener {
                doSignIn(activity, AGConnectAuthCredential.HMS_Provider)
            }
            ivGoogle.setOnClickListener {
                doSignIn(activity, AGConnectAuthCredential.Google_Provider)
            }
            ivFacebook.setOnClickListener {
                doSignIn(activity, AGConnectAuthCredential.Facebook_Provider)
            }
            show()
        }

    }

    override fun logout(activity: Activity, callback: (Int, String) -> Unit) {
        AGConnectAuth.getInstance().signOut()
        analytics.onEvent(HAEventType.SIGNOUT, null)
        callback(0, "用户登出成功")
    }

    override fun getOrderId(activity: Activity?, sdkChargeInfo: SdkChargeInfo, callback: (ResultInfo) -> Unit) {

    }

    override fun charge(activity: Activity, chargeInfo: SdkChargeInfo, isIab: Boolean, callback: (Int, String) -> Unit) {
    }

    override fun hasExitView(activity: Activity): Boolean = false

    override fun openExitView(activity: Activity, callback: (Int, String) -> Unit) {
    }

    override fun onDestroy(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onDestroy()
    }

    override fun getUserId(): String = ""

    override fun getChannelVersion(): String = "6.3.0.301"

    override fun getChannelName(): String = "huawei"

    override fun onStart(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onStart()
    }

    override fun onResume(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onResume()
        buoyClient?.showFloatWindow()
    }

    override fun onReStart(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onRestart()
    }

    override fun onPause(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onPause()
        buoyClient?.hideFloatWindow()
    }

    override fun onStop(activity: Activity) {
        AGConnectApi.getInstance().activityLifecycle().onStop()
    }

    override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data)
    }

    override fun onNewIntent(activity: Activity, intent: Intent?) {
        AGConnectApi.getInstance().activityLifecycle().onNewIntent(intent)
    }

    private fun doSignIn(activity: Activity, channel: Int) {
        showLoadingDialog(activity)
        AGConnectAuth.getInstance().signIn(activity, channel).addOnSuccessListener {
            // updateUI
            dismissLoadingDialog()
            loginDialog?.apply {
                dismiss()
                loginDialog = null
            }
            val channelName = when (channel) {
                AGConnectAuthCredential.HMS_Provider -> "huawei"
                AGConnectAuthCredential.Google_Provider -> "google"
                AGConnectAuthCredential.Facebook_Provider -> "facebook"
                else -> ""
            }
            val bundle = Bundle()
            bundle.putString(HAParamType.LOANCHANNEL, channelName)
            analytics.onEvent(HAEventType.SIGNIN, bundle)
        }.addOnFailureListener {
            // onFailure
            dismissLoadingDialog()
            Logger.e(it.localizedMessage)
            loginCallback(-1, "登录失败")
        }
    }

    private fun showLoadingDialog(context: Context) {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
        loadingDialog = ScaleLoadingDialog(context, "")
        loadingDialog?.show()
    }

    private fun dismissLoadingDialog() {
        loadingDialog?.apply {
            dismiss()
            loadingDialog = null
        }
    }


}