package com.narutohuo.xindazhou.common.ui

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import java.util.Stack

/**
 * Activity 管理器
 * 
 * 统一管理 Activity 栈，提供 Activity 生命周期管理和导航功能
 * 
 * 功能：
 * - Activity 栈管理（添加、移除、获取当前 Activity）
 * - 关闭指定 Activity
 * - 关闭所有 Activity
 * - 退出应用
 * - Activity 跳转封装
 * 
 * 使用方式：
 * ```kotlin
 * // 在 Application 中初始化
 * class MyApplication : Application() {
 *     override fun onCreate() {
 *         super.onCreate()
 *         ActivityManager.init(this)
 *     }
 * }
 * 
 * // 在 BaseActivity 中注册
 * override fun onCreate(savedInstanceState: Bundle?) {
 *     super.onCreate(savedInstanceState)
 *     ActivityManager.addActivity(this)
 * }
 * 
 * override fun onDestroy() {
 *     super.onDestroy()
 *     ActivityManager.removeActivity(this)
 * }
 * 
 * // 使用
 * ActivityManager.finishActivity(LoginActivity::class.java)
 * ActivityManager.finishAll()
 * ActivityManager.exitApp()
 * ```
 */
object ActivityManager {
    
    private val activityStack: Stack<Activity> = Stack()
    private var applicationContext: Context? = null
    
    /**
     * 初始化（在 Application.onCreate() 中调用）
     */
    fun init(context: Context) {
        applicationContext = context.applicationContext
    }
    
    /**
     * 添加 Activity 到栈
     */
    fun addActivity(activity: Activity) {
        activityStack.push(activity)
    }
    
    /**
     * 从栈中移除 Activity
     */
    fun removeActivity(activity: Activity) {
        activityStack.remove(activity)
    }
    
    /**
     * 获取当前 Activity（栈顶）
     */
    fun getCurrentActivity(): Activity? {
        return if (activityStack.isEmpty()) null else activityStack.peek()
    }
    
    /**
     * 获取 Activity 栈大小
     */
    fun getStackSize(): Int {
        return activityStack.size
    }
    
    /**
     * 关闭指定 Activity
     */
    fun finishActivity(activity: Activity) {
        if (activityStack.contains(activity)) {
            activityStack.remove(activity)
            activity.finish()
        }
    }
    
    /**
     * 关闭指定类型的 Activity
     */
    fun finishActivity(clazz: Class<out Activity>) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass == clazz) {
                iterator.remove()
                activity.finish()
                break
            }
        }
    }
    
    /**
     * 关闭所有指定类型的 Activity
     */
    fun finishAllActivities(clazz: Class<out Activity>) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass == clazz) {
                iterator.remove()
                activity.finish()
            }
        }
    }
    
    /**
     * 关闭除指定 Activity 外的所有 Activity
     */
    fun finishAllExcept(activity: Activity) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val current = iterator.next()
            if (current != activity) {
                iterator.remove()
                current.finish()
            }
        }
    }
    
    /**
     * 关闭除指定类型外的所有 Activity
     */
    fun finishAllExcept(clazz: Class<out Activity>) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass != clazz) {
                iterator.remove()
                activity.finish()
            }
        }
    }
    
    /**
     * 关闭所有 Activity
     */
    fun finishAll() {
        while (!activityStack.isEmpty()) {
            val activity = activityStack.pop()
            activity.finish()
        }
    }
    
    /**
     * 退出应用
     */
    fun exitApp() {
        finishAll()
        // 杀死进程
        android.os.Process.killProcess(android.os.Process.myPid())
        System.exit(0)
    }
    
    /**
     * 判断指定 Activity 是否存在
     */
    fun isActivityExist(clazz: Class<out Activity>): Boolean {
        return activityStack.any { it.javaClass == clazz }
    }
    
    /**
     * 获取指定类型的 Activity
     */
    fun getActivity(clazz: Class<out Activity>): Activity? {
        return activityStack.find { it.javaClass == clazz }
    }
    
    /**
     * 返回到指定 Activity
     */
    fun backToActivity(clazz: Class<out Activity>) {
        val iterator = activityStack.iterator()
        val activitiesToFinish = mutableListOf<Activity>()
        var found = false
        
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass == clazz) {
                found = true
                break
            } else {
                activitiesToFinish.add(activity)
            }
        }
        
        if (found) {
            activitiesToFinish.forEach { activity ->
                activityStack.remove(activity)
                activity.finish()
            }
        }
    }
    
    /**
     * 启动 Activity（封装 Intent）
     */
    fun startActivity(context: Context, clazz: Class<out Activity>) {
        val intent = Intent(context, clazz)
        if (context !is Activity) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
    }
    
    /**
     * 启动 Activity（带参数）
     */
    fun startActivity(
        context: Context,
        clazz: Class<out Activity>,
        block: Intent.() -> Unit
    ) {
        val intent = Intent(context, clazz).apply(block)
        if (context !is Activity) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
    }
    
    /**
     * 启动 Activity 并关闭当前
     */
    fun startActivityAndFinish(
        context: Context,
        clazz: Class<out Activity>
    ) {
        startActivity(context, clazz)
        if (context is Activity) {
            context.finish()
        }
    }
    
    /**
     * 启动 Activity 并关闭当前（带参数）
     */
    fun startActivityAndFinish(
        context: Context,
        clazz: Class<out Activity>,
        block: Intent.() -> Unit
    ) {
        startActivity(context, clazz, block)
        if (context is Activity) {
            context.finish()
        }
    }
    
    /**
     * 启动 Activity 并清空栈
     */
    fun startActivityAndClearTask(
        context: Context,
        clazz: Class<out Activity>
    ) {
        val intent = Intent(context, clazz).apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
        if (context is Activity) {
            context.finish()
        }
    }
    
    /**
     * 启动 Activity 并清空栈（带参数）
     */
    fun startActivityAndClearTask(
        context: Context,
        clazz: Class<out Activity>,
        block: Intent.() -> Unit
    ) {
        val intent = Intent(context, clazz).apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            block()
        }
        context.startActivity(intent)
        if (context is Activity) {
            context.finish()
        }
    }
    
    /**
     * 重启应用
     */
    fun restartApp() {
        val context = applicationContext ?: return
        val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
        intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        finishAll()
        context.startActivity(intent)
    }
}

