package com.renrenliao.im.provider

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Looper
import java.lang.ref.WeakReference

/**
 **@ClassName ActivityTracker
 **@Description TODO
 **@Author ganzhe
 **@Date 2022/5/19 15:18
 **/
class ActivityTracker {
    private val activities = mutableListOf<WeakReference<Activity>>()

    private val lifecycleCallbacks = object : ActivityLifecycleCallbacksAdapter() {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            add(activity)
        }

        override fun onActivityDestroyed(activity: Activity) {
            remove(activity)
        }
    }

    fun beginTracking(application: Application) {
        application.registerActivityLifecycleCallbacks(lifecycleCallbacks)
    }

    fun endTracking(application: Application) {
        application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks)
    }

    fun tryGetCurrentActivity(): Activity? {
        activities.reversed().forEach {
            val activity = it.get()
            if (activity != null) {
                return activity
            }
        }
        return null
    }

    private fun add(activity: Activity) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            activities.add(WeakReference(activity))
        } else {
            throw IllegalStateException("Must in Main Thread!")
        }
    }

    private fun remove(activity: Activity) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            removeFromWeakList(activities, activity)
        } else {
            throw IllegalStateException("Must in Main Thread!")
        }
    }

    private fun <T> removeFromWeakList(
        list: MutableList<WeakReference<T>>, needle: T
    ) {
        val find = list.find { it.get() === needle }
        list.remove(find)
    }

    fun finishAllActivity(){
        activities.forEach {
            it.get()?.finish()
        }
        activities.clear()
    }

    /**
     * 退出 app 时调用
     */
    fun exitApp() {
//        try {
//            finishAllActivity()
//            Process.killProcess(Process.myPid())
//            exitProcess(0)
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
        val intent =Intent(Intent.ACTION_MAIN)
        intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK
                or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
        intent.addCategory(Intent.CATEGORY_HOME)
        ClarityPotion.healingSalve.startActivity(intent)
    }
}