package com.base.scanqrclear.luma

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

object ActivityManagerHelps {
    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()
    }

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

    /**
     * 检查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 all: List<Activity>
        get() = activityStack

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