package com.rc.core.ui

import android.app.Activity
import java.util.ArrayList

/**
 * info
 *
 * @author ReiChin_
 */
object ActivityCollector {

    /**
     * 存放应用已开启的所有Activity.
     */
    private val mActivities by lazy { ArrayList<Activity>() }

    /**
     * 添加一个Activity到Activity列表中.
     *
     * @param activity
     * : Activity实例.
     */
    fun addActivity(activity: Activity) {
        mActivities.add(activity)
    }

    /**
     * 在Activity列表中，从顶部删除一定数量的Activity.
     * -1表示删除所有的Activity, 如果count大于Activity列表的size, 将删除所有的Activity.
     *
     * @param count
     * : 要删的Activity数量.
     */
    fun removeActivity(count: Int) {
        val listSize = mActivities.size
        val delCount = if (-1 == count || count > listSize) listSize else count
        for (i in 0 until delCount) {
            val activity = mActivities[listSize - i - 1]
            if (!activity.isFinishing) {
                activity.finish()
            }
            mActivities.remove(activity)
        }
    }

    /**
     * 从Activity列表中删除指定的Activity.
     *
     * @param activity
     * : 要删的Activity.
     */
    fun removeActivity(activity: Activity) {
        if (mActivities.contains(activity)) {
            mActivities.remove(activity)
        }
    }

    /**
     * 关闭所有的Activity, 退出程序.
     */
    fun finishAll() {
        for (activity in mActivities) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
        mActivities.clear()
    }

}