package com.base.utils.tools.android;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.base.utils.Config;
import com.base.utils.eventbusmodel.EventMimcRouse;
import com.base.utils.eventbusmodel.EventNoActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 管理
 */

public class ActivityUtil {
    /**
     * 得到当前应用程序处于前台还是后台
     * true = 后台
     * false = 前台
     */
    public static boolean appIsBackground(Context context) {
        //LogUtil.w(ActivityUtil.class, "appIsBackground true=后台,false =前台 现在的状态是：" + SPUtil.getBoolean(context, Config.spActivityUtilIsBackground));
        return SPUtil.getBoolean(context, Config.spActivityUtilIsBackground);
    }

    /**
     * 设置当前应用程序处于前台还是后台
     * true = 后台
     * false = 前台
     */
    public static void setAppIsBackground(Context context, boolean value) {
        SPUtil.setBoolean(context, Config.spActivityUtilIsBackground, value);
    }


    /**
     * 维护Activity 的list
     */
    private static List<Activity> mActivities = Collections.synchronizedList(new LinkedList<Activity>());

    public static int getActivitySize() {
        return mActivities.size();
    }


    /**
     * @param activity 作用说明 ：添加一个activity到管理里
     */
    public static void pushActivity(Activity activity) {
        mActivities.add(activity);
        LogUtil.w(ActivityUtil.class, "pushActivity:activityList:size:" + mActivities.size());
    }

    /**
     * @param activity 作用说明 ：删除一个activity在管理里
     */
    public static void popActivity(Activity activity) {
        mActivities.remove(activity);
        if (mActivities == null || mActivities.isEmpty()) {
            LogUtil.err(ActivityUtil.class, "程序结束，没有在线的Activity:" + activity);
            //EventBus只能处理正常情况下的Activity Finish
            EventBus.getDefault().post(new EventNoActivity());
            //如果用户是通过后台进程杀死
        } else if (mActivities.size() == 1) {
            EventBus.getDefault().post(new EventMimcRouse());
        }

    }


    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        if (mActivities == null || mActivities.isEmpty()) {
            return null;
        }
        return mActivities.get(mActivities.size() - 1);
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        if (mActivities == null || mActivities.isEmpty()) {
            return;
        }
        Activity activity = mActivities.get(mActivities.size() - 1);
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (mActivities == null || mActivities.isEmpty()) {
            return;
        }
        if (activity != null) {
            mActivities.remove(activity);
            activity.finish();
        }
    }

    /**
     * 得到指定的Activity
     *
     * @param cls 类
     */
    public static Activity getActivityByClassName(Class<?> cls) {
        if (mActivities == null || mActivities.isEmpty()) {
            return null;
        }
        for (Activity activity : mActivities) {
            if (activity.getClass().equals(cls)) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        if (mActivities == null || mActivities.isEmpty()) {
            return;
        }
        for (Activity activity : mActivities) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 按照指定类名找到activity
     *
     * @param cls
     * @return
     */
    public static Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (mActivities != null) {
            for (Activity activity : mActivities) {
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public static Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (mActivities) {
            final int size = mActivities.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivities.get(size);
        }
        return mBaseActivity;

    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    public static String getTopActivityName() {
        Activity mBaseActivity = null;
        synchronized (mActivities) {
            final int size = mActivities.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivities.get(size);
        }
        return mBaseActivity.getClass().getName();
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        if (mActivities == null) {
            return;
        }
        for (Activity activity : mActivities) {
            activity.finish();
        }
        mActivities.clear();
    }

    /**
     * 退出应用程序
     */
    public static void exit() {
        try {
            finishAllActivity();
            //这种方法退出应用，是会保留某些后进程,例如:Service,Notifications等。
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            LogUtil.err(ActivityUtil.class, "Exception:" + e.getMessage());
        }
    }

    /**
     * 退出应用程序
     */
    public static void exit(Context context) {
        try {
            finishAllActivity();
            ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); //获取应用程序管理器
            manager.killBackgroundProcesses(context.getPackageName()); //强制结束当前应用程序
            //这种方式退出应用，会结束本应用程序的一切活动,因为本方法会根据应用程序的包名杀死所有进程包括Activity,Service,Notifications等。
        } catch (Exception e) {
            LogUtil.err(ActivityUtil.class, "Exception:" + e.getMessage());
        }
    }

    /**
     * 注册监听
     */
    public static void registerActivityListener(Application application) {
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                /**
                 *  监听到 Activity创建事件 将该 Activity 加入list
                 */
                pushActivity(activity);

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (null == mActivities || mActivities.isEmpty()) {
                    return;
                }
                if (mActivities.contains(activity)) {
                    /**
                     *  监听到 Activity销毁事件 将该Activity 从list中移除
                     */
                    popActivity(activity);
                }
            }
        });
    }
}



