package cn.yyxx.eyuangame.core.linking.channel

import android.app.Activity
import android.app.Application
import android.content.Context
import android.text.TextUtils
import cn.yyxx.eyuangame.base.entity.SdkEvent
import cn.yyxx.eyuangame.base.utils.Logger
import cn.yyxx.eyuangame.base.utils.ParamsUtils
import cn.yyxx.eyuangame.core.entity.LoginType
import cn.yyxx.eyuangame.core.entity.SdkBackLoginInfo
import cn.yyxx.eyuangame.core.internal.IEventObserver
import cn.yyxx.eyuangame.core.utils.MMKVUtils
import cn.yyxx.support.JsonUtils
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * @author #Suyghur.
 * Created on 2021/06/17
 */
class LinkingAdjustImpl : IEventObserver {

    private var isInitSuccess = false
    private var sdkConfig: JSONObject? = null
    private var extConfig: JSONObject? = null


    override fun onInitialize(application: Application) {

        this.sdkConfig = getSdkLogJson(application)
        this.extConfig = getExtLogJson(application)

        if (sdkConfig == null) {
            Logger.e("adjust log 初始化失败，读取sdk_log.json异常")
            return
        }

        val appId = ParamsUtils.getAdjustAppId(application)
        if (TextUtils.isEmpty(appId)) {
            Logger.e("adjust log 初始化失败，app id为空")
            isInitSuccess = false
            return
        }

        val config = AdjustConfig(application, appId, AdjustConfig.ENVIRONMENT_PRODUCTION, true)
        config.setLogLevel(LogLevel.VERBOSE)
        Adjust.onCreate(config)
        if (MMKVUtils.instance.eventKV.decodeBool("adjust_activities")) {
            isInitSuccess = true
            return
        }
        sdkConfig?.apply {
            if (JsonUtils.hasJsonKey(this, "open_app")) {
                Adjust.trackEvent(AdjustEvent(this.getString("open_app")))
                Logger.d("adjust log open app success")
                MMKVUtils.instance.eventKV.encode("adjust_activities", true)
                isInitSuccess = true
            }
        }
    }

    override fun onLogin(context: Context) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.userId)) {
            Logger.e("adjust log failed , user is null")
            return
        }

        sdkConfig?.apply {
            when (SdkBackLoginInfo.instance.loginType) {
                LoginType.TYPE_GUEST_LOGIN -> {
                    if (JsonUtils.hasJsonKey(this, "login_success_quick")) {
                        Adjust.trackEvent(AdjustEvent(this.getString("login_success_quick")))
                        Logger.d("adjust log guest login success")
                    }
                }
                LoginType.TYPE_FACEBOOK_LOGIN -> {
                    if (JsonUtils.hasJsonKey(this, "login_success_fb")) {
                        Adjust.trackEvent(AdjustEvent(this.getString("login_success_fb")))
                        Logger.d("adjust log facebook login success")
                    }
                }
                LoginType.TYPE_GOOGLE_LOGIN -> {
                    if (JsonUtils.hasJsonKey(this, "login_success_google")) {
                        Adjust.trackEvent(AdjustEvent(this.getString("login_success_google")))
                        Logger.d("adjust log google login success")
                    }
                }
                LoginType.TYPE_ACCOUNT_LOGIN -> {
                    if (JsonUtils.hasJsonKey(this, "login_success_account")) {
                        Adjust.trackEvent(AdjustEvent(this.getString("login_success_account")))
                        Logger.d("adjust log account login success")
                    }
                }
            }
        }
    }

    override fun onRegister(context: Context) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.userId)) {
            Logger.e("adjust log failed , user is null")
            return
        }

        sdkConfig?.apply {
            if (JsonUtils.hasJsonKey(this, "sign_up")) {
                Adjust.trackEvent(AdjustEvent(this.getString("sign_up")))
                Logger.d("adjust log register success")
            }
        }
    }

    override fun onCharge(context: Context, amount: Int) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.userId)) {
            Logger.e("adjust log failed , user is null")
            return
        }

        sdkConfig?.apply {
            if (!MMKVUtils.instance.eventKV.decodeBool("adjust_first_purchase")) {
                if (JsonUtils.hasJsonKey(this, "first_purchase")) {
                    val event = AdjustEvent(this.getString("first_purchase"))
                    event.setRevenue(amount.toDouble() / 100, "USD")
                    Adjust.trackEvent(event)
                    Logger.d("adjust log first charge success")
                    MMKVUtils.instance.eventKV.encode("adjust_first_purchase", true)
                }
            }

            if (JsonUtils.hasJsonKey(this, "ecommerce_purchase")) {
                val event = AdjustEvent(this.getString("ecommerce_purchase"))
                event.setRevenue(amount.toDouble() / 100, "USD")
                Adjust.trackEvent(event)
                Logger.d("adjust log charge success")
            }
        }
    }

    override fun onRoleCreate(context: Context) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.userId)) {
            Logger.e("adjust log failed , user is null")
            return
        }

        sdkConfig?.apply {
            if (JsonUtils.hasJsonKey(this, "create_player")) {
                Adjust.trackEvent(AdjustEvent(this.getString("create_player")))
                Logger.d("adjust log create player success")
            }
        }
    }

    override fun onRoleLauncher(context: Context) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        if (TextUtils.isEmpty(SdkBackLoginInfo.instance.userId)) {
            Logger.e("adjust log failed , user is null")
            return
        }

        sdkConfig?.apply {
            if (JsonUtils.hasJsonKey(this, "enter_game")) {
                Adjust.trackEvent(AdjustEvent(this.getString("enter_game")))
                Logger.d("adjust log enter game success")
            }
        }
    }

    override fun onCreate(activity: Activity) {
    }

    override fun onResume(activity: Activity) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }
        Adjust.onResume()
    }

    override fun onPause(activity: Activity) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }
        Adjust.onPause()
    }

    override fun onSdkEvent(context: Context, sdkEvent: SdkEvent) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        sdkConfig?.apply {
            if (JsonUtils.hasJsonKey(this, sdkEvent.eventName)) {
                Adjust.trackEvent(AdjustEvent(this.getString(sdkEvent.eventName)))
                Logger.d("adjust log sdk event ${sdkEvent.eventName} success")
            }
        }
    }

    override fun onExtEvent(context: Context, sdkEvent: SdkEvent) {
        if (!isInitSuccess) {
            Logger.e("adjust log failed , component initialize failed")
            return
        }

        extConfig?.apply {
            if (JsonUtils.hasJsonKey(this, sdkEvent.eventName)) {
                Adjust.trackEvent(AdjustEvent(this.getString(sdkEvent.eventName)))
                Logger.d("adjust log ext event ${sdkEvent.eventName} success")
            }
        }
    }

    private fun getSdkLogJson(context: Context): JSONObject? {
        val path = "yyxx_game/sdk_log.json"
        val sb = StringBuilder()
        try {
            val assetManager = context.assets
            BufferedReader(InputStreamReader(assetManager.open(path))).use {
                var line = ""
                while (true) {
                    line = it.readLine() ?: break
                    sb.append(line)
                }
            }
            if (!TextUtils.isEmpty(sb.toString())) {
                return JSONObject(sb.toString())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun getExtLogJson(context: Context): JSONObject? {
        val path = "yyxx_game/ext_log.json"
        val sb = StringBuilder()
        try {
            val assetManager = context.assets
            BufferedReader(InputStreamReader(assetManager.open(path))).use {
                var line = ""
                while (true) {
                    line = it.readLine() ?: break
                    sb.append(line)
                }
            }
            if (!TextUtils.isEmpty(sb.toString())) {
                return JSONObject(sb.toString())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}