package com.base.datarecovery.utils

import android.app.Activity
import java.util.Stack

object ActivityManagerUtils {
    private val activityStack = Stack<Activity>()

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity) {
        activityStack.add(activity)
    }

    /**
     * 移除Activity从堆栈
     */
    fun removeActivity(activity: Activity) {
        activityStack.remove(activity)
    }

    val currentActivity: Activity
        /**
         * 获取当前Activity（堆栈中最后一个压入的）
         */
        get() = activityStack.lastElement()

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            activityStack.remove(activity)
            activity.finish()
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        for (activity in activityStack) {
            activity?.finish()
        }
        activityStack.clear()
    }

    /**
     * 检查Activity是否存在于堆栈中
     */
    fun isActivityInStack(cls: Class<*>?): Boolean {
        var isExist = false
        if (cls != null) {
            for (activity in activityStack) {
                if (cls == activity.javaClass) {
                    isExist = true
                    break
                }
            }
        }
        return isExist
    }

    val topActivity: Activity?
        get() = if (activityStack.empty()) {
            null
        } else {
            activityStack.peek()
        }


    fun finishAll(excludeCls: Class<*>?) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val item = iterator.next()
            if (excludeCls != item.javaClass) {
                item.finish()
                iterator.remove()
            }
        }
    }
}