package com.img.rabbit.utils

import android.content.Context
import android.content.pm.PackageManager
import android.text.TextUtils
import com.bytedance.hume.readapk.HumeSDK
import com.img.rabbit.BuildConfig
import com.kwai.monitor.payload.TurboHelper
import com.tencent.vasdolly.helper.ChannelReaderUtil


object ChannelUtils {

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

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

    private fun channel(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 ""
    }

}

