package com.cheng.blzb.utils

import android.content.Context
import android.content.pm.PackageManager
import android.text.TextUtils
import com.bytedance.hume.readapk.HumeSDK
import com.cheng.blzb.BuildConfig
import com.example.base.utils.MMKVUtils
import com.example.base.utils.Utils
import com.kwai.monitor.payload.TurboHelper
import com.tencent.vasdolly.helper.ChannelReaderUtil


object ChannelUtils {

    fun getChannel(): String {
        if (BuildConfig.DEBUG) {
            MMKVUtils.put("app_channel", "test")
        } else {
            if (TextUtils.isEmpty(MMKVUtils.getString("app_channel"))) {
                MMKVUtils.put("app_channel", getChannelBy())
            }
        }
        return MMKVUtils.getString("app_channel") ?: ""
    }

    private fun getChannelBy(): String? {
        val kuaishou = TurboHelper.getChannel(Utils.getApp())
        if (!TextUtils.isEmpty(kuaishou)) {
            return kuaishou
        }
        val tengxun = ChannelReaderUtil.getChannel(Utils.getApp())
        if (!TextUtils.isEmpty(tengxun)) {
            return tengxun
        }
        val juliang = HumeSDK.getChannel(Utils.getApp())
        if (!TextUtils.isEmpty(juliang)) {
            return juliang
        }
        return getChannel(Utils.getApp())
    }

    private fun getChannel(context: Context): String {
        try {
            val pm = context.packageManager
            val appInfo = pm.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            val channel = appInfo.metaData.getString("UMENG_CHANNEL")
            if (!TextUtils.isEmpty(channel)) {
                return channel!!
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

}

