package cn.yyxx.eyuancomm.comm

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.webkit.WebView
import cn.yyxx.eyuancomm.Version
import cn.yyxx.eyuancomm.base.entity.Function
import cn.yyxx.eyuancomm.base.entity.SdkChargeInfo
import cn.yyxx.eyuancomm.base.entity.SdkEvent
import cn.yyxx.eyuancomm.base.entity.SdkRoleInfo
import cn.yyxx.eyuancomm.base.internal.ICallback
import cn.yyxx.eyuancomm.base.utils.Logger
import cn.yyxx.eyuancomm.comm.impl.CommSdkImpl
import cn.yyxx.support.AppUtils

/**
 * @author #Suyghur.
 * Created on 2021/06/09
 */
class EYuanCommSdk private constructor() {

    private var commSdkImpl: CommSdkImpl? = null
    private var processName: String = ""
    private var clickLoginTime = 0L
    private var clickLogoutTime = 0L
    private var clickChargeTime = 0L

    companion object {
        private const val CLICK_INTERVAL: Int = 1500

        @JvmStatic
        fun getInstance(): EYuanCommSdk {
            return EYuanCommSdkHolder.INSTANCE
        }

        private object EYuanCommSdkHolder {
            val INSTANCE: EYuanCommSdk = EYuanCommSdk()
        }

        /**
         * 防止单例对象在反序列化时重新生成对象
         */
        private fun readResolve(): Any {
            return EYuanCommSdkHolder.INSTANCE
        }
    }

    /**
     * 同步Application中的attachBaseContext
     */
    fun attachBaseContext(application: Application, context: Context) {
        if (TextUtils.isEmpty(processName)) {
            this.processName = AppUtils.getProcessName(application)
        }
        if (TextUtils.isEmpty(processName) || processName != context.packageName) {
            return
        }
        if (commSdkImpl == null) {
            commSdkImpl = CommSdkImpl(application)
        }
        commSdkImpl?.attachBaseContext(application, context)
    }


    /**
     * 同步Application中的onCreate
     */
    fun initApplication(application: Application) {
        if (TextUtils.isEmpty(processName)) {
            this.processName = AppUtils.getProcessName(application)
        }
        //处理Android P webView的坑
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try {
                if (application.packageName != processName) {
                    WebView.setDataDirectorySuffix(processName)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        if (TextUtils.isEmpty(processName) || processName != application.packageName) {
            return
        }
        if (commSdkImpl == null) {
            commSdkImpl = CommSdkImpl(application)
        }
        commSdkImpl?.initApplication(application)
    }

    /**
     * SDK初始化
     *
     * @param activity    Activity上下文
     * @param isLandscape 是否横屏
     * @param callback    SDK初始化回调
     */
    fun initialize(activity: Activity, isLandscape: Boolean, callback: ICallback) {
        if (checkSdkImplNull(Function.INITIALIZE, callback)) {
            return
        }

        commSdkImpl?.initialize(activity, isLandscape, callback)
    }

    /**
     * SDK用户登录
     *
     * @param activity Activity上下文
     * @param callback 登录回调对象
     */
    fun login(activity: Activity, callback: ICallback) {
        if (checkSdkImplNull(Function.LOGIN, callback)) {
            return
        }

        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            Logger.e("调用登录接口太频繁，拦截此次操作")
            callback.onResult(-1, "调用登录接口太频繁")
            return
        }

        clickLoginTime = System.currentTimeMillis()
        commSdkImpl?.login(activity, callback)
    }

    /**
     * SDK用户登出账号
     *
     * @param activity Activity上下文
     * @param callback 登出回调对象
     */
    fun logout(activity: Activity, callback: ICallback) {
        if (checkSdkImplNull(Function.LOGOUT, callback)) {
            return
        }

        if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
            Logger.e("调用登录接口后，调用登出账号接口间隔太短，拦截此次操作")
            callback.onResult(-1, "调用登录接口后，调用登出账号接口间隔太短")
            return
        }

        if (System.currentTimeMillis() - clickLogoutTime < CLICK_INTERVAL) {
            Logger.e("调用登出账号接口太频繁，拦截此次操作")
            callback.onResult(-1, "调用登出账号接口太频繁")
            return
        }

        clickLogoutTime = System.currentTimeMillis()
        commSdkImpl?.logout(activity, callback)
    }

    /**
     * SDK用户支付
     *
     * @param activity   Activity上下文
     * @param chargeInfo 支付信息实体对象
     * @param isIab      是否内购
     * @param callback   支付回调对象
     */
    fun charge(activity: Activity, chargeInfo: SdkChargeInfo, isIab: Boolean, callback: ICallback) {
        if (checkSdkImplNull(Function.CHARGE, callback)) {
            return
        }

        if (System.currentTimeMillis() - clickChargeTime < CLICK_INTERVAL) {
            Logger.e("调用充值接口太频繁，拦截此次操作")
            callback.onResult(-1, "调用充值接口太频繁")
            return
        }

        clickChargeTime = System.currentTimeMillis()
        commSdkImpl?.charge(activity, chargeInfo, isIab, callback)
    }

    /**
     * SDK角色创建信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     */
    fun roleCreate(activity: Activity, roleInfo: SdkRoleInfo) {
        if (checkSdkImplNull(Function.ROLE_CREATE, null)) {
            return
        }
        commSdkImpl?.roleCreate(activity, roleInfo)
    }

    /**
     * SDK角色登录信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     */
    fun roleLauncher(activity: Activity, roleInfo: SdkRoleInfo) {
        if (checkSdkImplNull(Function.ROLE_LAUNCHER, null)) {
            return
        }
        commSdkImpl?.roleLauncher(activity, roleInfo)
    }

    /**
     * SDK角色升级信息上报
     *
     * @param activity Activity上下文
     * @param roleInfo 角色信息实体
     */
    fun roleLevelUp(activity: Activity, roleInfo: SdkRoleInfo) {
        if (checkSdkImplNull(Function.ROLE_LEVEL_UP, null)) {
            return
        }
        commSdkImpl?.roleLevelUp(activity, roleInfo)
    }

    /**
     * 是否有渠道退出框
     *
     * @param activity Activity上下文
     */
    fun hasExitView(activity: Activity): Boolean {
        return if (checkSdkImplNull(Function.HAS_EXIT_VIEW, null)) {
            false
        } else {
            commSdkImpl!!.hasExitView(activity)
        }
    }

    /**
     * 显示退出框
     *
     * @param activity Activity上下文
     * @param callback 退出回调对象
     */
    fun openExitView(activity: Activity, callback: ICallback) {
        if (checkSdkImplNull(Function.OPEN_EXIT_VIEW, callback)) {
            return
        }
        commSdkImpl?.openExitView(activity, callback)
    }

    fun onStart(activity: Activity) {
        if (checkSdkImplNull(Function.ON_START, null)) {
            return
        }
        commSdkImpl?.onStart(activity)
    }

    fun onRestart(activity: Activity) {
        if (checkSdkImplNull(Function.ON_RESTART, null)) {
            return
        }
        commSdkImpl?.onRestart(activity)
    }

    fun onResume(activity: Activity) {
        if (checkSdkImplNull(Function.ON_RESUME, null)) {
            return
        }
        commSdkImpl?.onResume(activity)
    }

    fun onPause(activity: Activity) {
        if (checkSdkImplNull(Function.ON_PAUSE, null)) {
            return
        }
        commSdkImpl?.onPause(activity)
    }

    fun onStop(activity: Activity) {
        if (checkSdkImplNull(Function.ON_STOP, null)) {
            return
        }
        commSdkImpl?.onStop(activity)
    }

    fun onDestroy(activity: Activity) {
        if (checkSdkImplNull(Function.ON_DESTROY, null)) {
            return
        }
        commSdkImpl?.onDestroy(activity)
    }

    fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
        if (checkSdkImplNull(Function.ON_ACTIVITY_RESULT, null)) {
            return
        }
        commSdkImpl?.onActivityResult(activity, requestCode, resultCode, data)
    }

    fun onNewIntent(activity: Activity, intent: Intent?) {
        if (checkSdkImplNull(Function.ON_NEW_INTENT, null)) {
            return
        }
        commSdkImpl?.onNewIntent(activity, intent)
    }

    fun getCurrentUserId(): String {
        return if (checkSdkImplNull(Function.GET_CURRENT_USER_ID, null)) {
            return ""
        } else {
            commSdkImpl!!.getCurrentUserId()
        }
    }

    fun getSdkVersion(): String {
        return Version.VERSION_NAME
    }

    fun linkingEvent(context: Context, sdkEvent: SdkEvent) {
        if (checkSdkImplNull(Function.LINKING_EVENT, null)) {
            return
        }
        commSdkImpl?.linkingEvent(context, sdkEvent)
    }

    fun share(activity: Activity, line: String, tag: String, quote: String, callback: ICallback) {
        if (checkSdkImplNull(Function.SHARE, null)) {
            return
        }
        commSdkImpl?.share(activity, line, tag, quote, callback)
    }

    private fun checkSdkImplNull(function: String, callback: ICallback?): Boolean {
        return if (commSdkImpl == null) {
            Logger.e("invoke $function error ... EYuanGameSdk initialized failed or not initialized yet")
            callback?.onResult(-1, "EYuanGameSdk 初始化失败或还未进行初始化")
            true
        } else {
            false
        }
    }
}