package com.beanpodtech.allinone.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;


import com.beanpodtech.allinone.activity.LoginActivity;

import java.util.Iterator;
import java.util.Stack;

/**
 * activity 管理中心(栈管理)
 */
public enum AppUtil {

    INSTANCE;
    private static Stack<Activity> activityStack;

    //入栈
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    //获取栈顶
    public Activity getTopActivity() {
        Activity activity = null;
        if (null != activityStack && 0 != activityStack.size()) {
            activity = activityStack.lastElement();
        }
        return activity;
    }

    /**
     * 得到指定类名的Activity
     */
    public Activity getActivity(Class<?> cls) {

        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 结束栈顶Activity（堆栈中最后一个压入的）
     */
    public void finishTopActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {

        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        Iterator iterator = activityStack.iterator();
        while (iterator.hasNext()) {
            Activity activity = (Activity) iterator.next();
            if (activity.getClass().equals(cls)) {
                iterator.remove();
                activity.finish();
            }
        }
    }

    /**
     * 结束所有Activity
     */
    @SuppressWarnings("WeakerAccess")
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void appExit() {
        finishAllActivity();
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 退出登录
     *
     * @param context
     */
    public void LoginOut(Context context) {

        if (!getTopActivity().getClass().equals(LoginActivity.class)) {
            Intent mIntent = new Intent(context, LoginActivity.class);
            context.startActivity(mIntent);
            finishAllActivity();
        }
    }
}
