package com.ym.game.application;


import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Process
import android.text.TextUtils
import android.util.Log
import androidx.multidex.MultiDex
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.ym.admodule.config.AdManager
import com.ym.library.MyConstant
import com.ym.modulecommon.AppLibraryConfig
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.base.BaseApplication
import com.ym.modulecommon.base.SplashResumeActivity
import com.ym.modulecommon.net.NetConfig
import com.ym.modulecommon.utils.LogUtils
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

class BaseApplication : BaseApplication() {
    // 正常状态
    val STATE_NORMAL = 0

    // 从后台回到前台
    val STATE_BACK_TO_FRONT = 1

    // 从前台进入后台
    val STATE_FRONT_TO_BACK = 2

    // APP状态
    private var sAppState = STATE_NORMAL

    // 标记程序是否已进入后台(依据onStop回调)
    private var flag = false

    // 标记程序是否已进入后台(依据onTrimMemory回调)
    private var background = false

    // 从前台进入后台的时间
    private var frontToBackTime: Long = 0

    // 从后台返回前台的时间
    private var backToFrontTime: Long = 0
    override fun onCreate() {
        super.onCreate()
        NetConfig.setBase_Url(NetConfig.Environment.DEV)// TODO 上线之后提成成  NetConfig.Environment.PRODUCT

        var isDebug = true
        if (NetConfig.sEnvironment == NetConfig.Environment.PRODUCT) {
            isDebug = false
//            NetConfig.BASE_FEED_URL = "https://fsapi.ihuomao.com/"
//            NetConfig.BASE_AD_URL = "https://bs.ihuomao.com/"
//            NetConfig.URL_REPORT_BASE = "http://report.ihuomao.com/"
        } else {
            NetConfig.BASE_FEED_URL = "http://feedapitest3.zhangxinhulian.com/"
        }


        //TODO 上线去掉测试地址
//        Constant.appLs = "b59e7d03c0f91730"//appls
        AdManager.init(this, "1d8a0d53c33a9b95")
        LogUtils.getConfig().logSwitch = isDebug
        UMConfigure.setLogEnabled(false)
        UMConfigure.init(this, "5fe446a944bb94418a636569", "", UMConfigure.DEVICE_TYPE_PHONE, "")
        PlatformConfig.setWeixin(MyConstant.WX_APPID, MyConstant.WX_APPKEY)
        AppLibraryConfig.ActivityConfig.isProhibitScreenshot=false

        //========== Bugly ==========
        val strategy = CrashReport.UserStrategy(this)
        strategy.appChannel = getChannelDada()
        // 获取当前包名
        val packageName = packageName
        // 获取当前进程名
        val processName = getProcessName(Process.myPid())
        // 设置是否为上报进程
        strategy.isUploadProcess = processName == null || processName == packageName
        //Bugly初始化
        CrashReport.initCrashReport(this, "3bac59d22f", isDebug, strategy)
        //========== Bugly ==========

        //小满
//        AdSdk.setDebug(isDebug)//打开日志
//        AdSdk.init(this, "ddhy-az-hdgj_vbskkc", "D545402QovC2W5g8")//初始化 需要在Applicaiton 中
        //registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(base)
    }

    /**
     * 当前Activity个数
     */
    private var activityCount = 0
    var activityLifecycleCallbacks: Application.ActivityLifecycleCallbacks =
        object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {

                if (background || flag) {
                    background = false
                    flag = false
                    sAppState = STATE_BACK_TO_FRONT
                    backToFrontTime = System.currentTimeMillis()
                    if (canShowAd()) {
                        var intent = Intent()
                        intent.setClass(applicationContext, SplashResumeActivity::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        AppliContext.get().startActivity(intent)
                    }

                } else {
                    sAppState = STATE_NORMAL
                }

                activityCount++
            }

            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {
                if (!isCurAppTop(activity)) {
                    // 从前台进入后台
                    sAppState = STATE_FRONT_TO_BACK;
                    frontToBackTime = System.currentTimeMillis();
                    flag = true;
                } else {
                    // 否则是正常状态
                    sAppState = STATE_NORMAL;
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        }

    fun canShowAd(): Boolean {
        return sAppState === STATE_BACK_TO_FRONT &&
                backToFrontTime - frontToBackTime > 10000
    }

    fun isCurAppTop(context: Context?): Boolean {
        if (context == null) {
            return false
        }
        val curPackageName = context.packageName
        val am: ActivityManager =
            context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list: List<ActivityManager.RunningTaskInfo> = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val info: ActivityManager.RunningTaskInfo = list[0]
            val topPackageName: String = info?.topActivity?.packageName!!
            val basePackageName: String = info.baseActivity?.packageName!!
            if (topPackageName == curPackageName && basePackageName == curPackageName) {
                return true
            }
        }
        return false
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName: String = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                if (reader != null) {
                    reader.close()
                }
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }

    //获取apk渠道
    private fun getChannelDada(): String {
        val packageManager = packageManager
        val applicationInfo =
            packageManager?.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        val string = applicationInfo?.metaData?.getString("UMENG_CHANNEL")
        Log.i("Application", "Channel = $string")
        return string ?: ""
    }
}