package com.sheep.gamegroup.util;

import android.app.Activity;

import java.util.Stack;

/**
 * Created by ljy on 2018/3/12.
 */

public class ActivityManager {
    /**
     * activity的Stack
     */
    private static Stack<Activity> activityStack = new Stack<>();
    private static ActivityManager activityManager;

    public static ActivityManager getInstance() {
        if (activityManager == null)
            activityManager = new ActivityManager();
        return activityManager;
    }

    /**
     * 将activity移除stack
     */
    public void popActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }
    }

    /**
     * 结束制定activity
     */
    public void endActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束制定activity
     */
    public void endActivity(Class<? extends Activity> cls) {
        try {
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    endActivity(activity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 活的当前的activity(即最上层)
     */
    public Activity currentActivity() {
        Activity activity = null;
        if (!activityStack.empty()) {
            activity = activityStack.lastElement();
        }
        return activity;
    }

    /**
     * 讲activity 推入栈内
     */
    public void pushActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    /**
     * 弹出class外的所有activity
     */
    public void popAllActivityExceptThis(Class<? extends Activity> cls) {
        while (true) {
            Activity activity = currentActivity();
            if (activity == null) {
                break;
            }
            if (activity.getClass().equals(cls)) {
                break;
            }
            popActivity(activity);
        }
    }

    /**
     * 结束除cls之外的所有activity,将执行结果都会清空stack
     */
    public void finishAllActivityExceptThis(Class<? extends Activity> cls) {
        while (!activityStack.empty()) {
            Activity activity = currentActivity();
            if (activity.getClass().equals(cls)) {
                popActivity(activity);
            } else {
                endActivity(activity);
            }
        }
    }

    /**
     * 结束所有activity
     */
    public void finishAllActivity() {
        while (!activityStack.empty()) {
            Activity activity = currentActivity();
            endActivity(activity);
        }
    }
}
