package com.zxhl.xymhhf

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import com.umeng.socialize.PlatformConfig
import com.zx.ad.modulecommon.AdNetConfig
import com.zxbw.modulemain.activity.XymhSplashBackgroundActivity
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.ApplicationAsLibrary
import com.zxhl.cms.common.Config
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.utils.EventUtils.onEvent
import com.zxhl.cms.utils.MiitHelper
import com.zxhl.cms.utils.Utils
import java.util.*


/**
 * Created by gaoleichao on 2018/12/26
 */
class Appli : Application() {
    private val mChildApplicationList = ArrayList<ApplicationAsLibrary>()
    // 正常状态
    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()
        AppContext.init(applicationContext)
        AdNetConfig.setBase_Url(AdNetConfig.Environment.PRODUCT)
        if (!SettingPreference.getFirstApp()) {
            initAppConfig()
        }
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
        val helper = XymhAppFrontBackHelper()

        helper.register(this, object : XymhAppFrontBackHelper.OnAppStatusListener {
            override fun onFront() {
                //应用切到前台处理
                Log.e("MXL", "应用切到前台处理")
//                val intent = Intent(AppContext.get(), PlayingMusicServices::class.java)
//                intent.putExtra("type", 1)
//                startService(intent)
            }

            override fun onBack() {
                Log.e("MXL", "应用切到后台处理")
                //启动服务，播放音乐
//                val intent = Intent(AppContext.get(), PlayingMusicServices::class.java)
//                intent.putExtra("type", 2)
//                startService(intent)
            }
        })

    }

    private fun getOaid() {
        MiitHelper(appIdsUpdater).getDeviceIds(AppContext.mAppContext)
    }

    private val appIdsUpdater: MiitHelper.AppIdsUpdater = object : MiitHelper.AppIdsUpdater {
        override fun OnIdsAvalid(ids: String) {
            if (!TextUtils.isEmpty(ids)) {
                SettingPreference.setOaid(ids)
                onEvent("tab_imp", "获取到oaid$ids")
            }
        }
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
//        for (app in mChildApplicationList) {
//            app.onTrimMemoryAsLibrary(this, level)
//        }
    }

    override fun onLowMemory() {
        super.onLowMemory()
//        for (app in mChildApplicationList) {
//            app.onLowMemoryAsLibrary(this)
//        }
    }

    fun initAppConfig(){
        UMConfigure.init(AppContext.get(), UMConfigure.DEVICE_TYPE_PHONE, "")
        Utils.checkDebugMode(AppContext.get())
        PlatformConfig.setWeixin(Constant.WX_APPID, Constant.WX_APPKEY)
        PlatformConfig.setWXFileProvider("com.tencent.sample2.fileprovider");
        Config.init(AppContext.get())
        //初始化bugly
        CrashReport.initCrashReport(AppContext.get(), "f9fb9a9ef5", false);
        getOaid()
    }
    /**
     * 当前Activity个数
     */
    private var activityCount = 0
    var activityLifecycleCallbacks: ActivityLifecycleCallbacks =
        object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityStarted(activity: Activity) {
                if (activityCount === 0) {//从后台进入前台
                    Constant.Utils.isTimingReport = true
                }
                activityCount++

                if (background || flag) {
                    background = false
                    flag = false
                    sAppState = STATE_BACK_TO_FRONT
                    backToFrontTime = System.currentTimeMillis()
                    if(canShowAd()){
                        Log.e("MXL","加载开屏")
                        var intent = Intent()
                        intent.setClass(applicationContext, XymhSplashBackgroundActivity::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        AppContext.get().startActivity(intent)
                    }
                } else {
                    sAppState = STATE_NORMAL
                }
            }
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {
                activityCount--
                if (activityCount === 0) {//进入后台
                    Constant.Utils.isTimingReport = false
                }

                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
    }
}