package com.example.defenseapplication.utils

import android.app.Activity
import java.lang.ref.WeakReference
import java.util.Stack

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

    fun addActivity(activity: Activity) {
        activityStack.push(WeakReference(activity))
    }

    fun removeActivity(activity: Activity) {
        activityStack.removeIf { it.get() == activity }
    }

    fun finishActivity(activity: Activity) {
        activity.finish()
        removeActivity(activity)
    }

    fun finishAllActivities() {
        while (activityStack.isNotEmpty()) {
            val activityRef = activityStack.pop()
            activityRef.get()?.finish()
        }
        activityStack.clear()
    }

    fun finishToActivity(cls: Class<*>) {
        val tempStack = Stack<WeakReference<Activity>>()
        
        while (activityStack.isNotEmpty()) {
            val activityRef = activityStack.pop()
            val activity = activityRef.get()
            
            if (activity != null && activity.javaClass == cls) {
                tempStack.push(activityRef)
                break
            } else if (activity != null) {
                activity.finish()
            }
        }
        
        while (tempStack.isNotEmpty()) {
            activityStack.push(tempStack.pop())
        }
    }

    fun finishExceptHome() {
        val tempStack = Stack<WeakReference<Activity>>()
        var foundHome = false
        
        while (activityStack.isNotEmpty()) {
            val activityRef = activityStack.pop()
            val activity = activityRef.get()
            
            if (activity != null) {
                val className = activity.javaClass.simpleName
                if (className == "HomeActivity" || className == "MainActivity") {
                    tempStack.push(activityRef)
                    foundHome = true
                    break
                } else {
                    activity.finish()
                }
            }
        }
        
        if (!foundHome) {
            while (tempStack.isNotEmpty()) {
                activityStack.push(tempStack.pop())
            }
        } else {
            while (tempStack.isNotEmpty()) {
                activityStack.push(tempStack.pop())
            }
        }
    }

    fun getCurrentActivity(): Activity? {
        if (activityStack.isEmpty()) {
            return null
        }
        return activityStack.peek().get()
    }

    fun getActivityCount(): Int {
        return activityStack.size
    }
}