package com.zxdemo.utils
import android.app.Activity
import java.util.Stack

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

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

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

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

    /**
     * 结束所有Activity
     */
    fun finishAll() {
        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
    }

    fun getAll(): List<Activity> {
        return activityStack
    }

    fun getTopActivity(): Activity? {
        return if (activityStack.isEmpty()) {
            null
        } else {
            activityStack.peek()
        }
    }
}