package com.ydl.ydlcommon.utils

import android.app.Activity

/**
 * activity 管理类
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/02/05
 */
class ActivityManager {

    companion object {
        fun getInstance(): ActivityManager {
            return Holder.INSTANCE
        }

        fun getActivitySize(): Int {
            return getInstance().activates.size
        }

        fun finishAll() {
            for(a in getInstance().activates) {
                a.finish()
            }
            getInstance().activates.clear()
        }

        fun finishActivity(activity: Activity) {
            if (getInstance().activates.contains(activity)) {
                getInstance().activates.remove(activity)
                activity.finish()
            }
        }

        /**
         * 关闭除当前activity外的所有activity
         */
        fun finishOtherActivity(activity: Activity) {

            for (act in getInstance().activates){
                if (act == activity)continue
                act.finish()
            }
        }

        fun finishActivity(cls: Class<*>) {
            getInstance().activates
                    .filter { it::class.java == cls }
                    .forEach { finishActivity(it) }
        }
    }

    private val activates: MutableList<Activity> by lazy {
        ArrayList<Activity>()
    }

    // 添加到栈中
     fun addStack(activity: Activity) {
        activates.add(activity)
    }

    // 从栈中移除
    internal fun removeStack(activity: Activity) {
        if (activates.contains(activity)) {
            activates.remove(activity)
        }
    }

    fun getTopTaskActivity(): Activity {
        return activates[activates.size - 1]
    }

    fun getSecondTaskActivity(): Activity? {
        return if (activates.size <= 1) {
            null
        } else {
            activates[activates.size - 2]
        }
    }

    fun finishTopActivity(num: Int) {
        if (activates.isEmpty()) {
            return
        }
        val size = Math.min(num, activates.size)
        (0 until size).forEach { activates[it].finish() }
    }

    fun finishActivity(activity: Activity) {
        if (activates.contains(activity)) {
            activates.remove(activity)
            activity.finish()
        }
    }

    fun getActivitys(): MutableList<Activity> {
        return activates
    }

    fun finishActivity(cls: Class<out Activity>) {
        activates.filter { it::class.java == cls }
                .forEach { finishActivity(it) }
    }

    private object Holder {
        internal val INSTANCE = ActivityManager()
    }
}