package com.sxyz.rfid.widgets;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;


import com.sxyz.rfid.utils.DensityUtils;

import java.util.List;

/**
 * app生命周期全局监听(判断app是否处于后台)
 */
public class MyActivityLifecycle implements Application.ActivityLifecycleCallbacks {
    private Context mContext;

    public MyActivityLifecycle(Context mContext) {
        this.mContext = mContext;
    }

    private boolean wasOpened = false;
    private final static int KEYBOARD_VISIBLE_THRESHOLD_DP = 100;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//        try {
//            final View activityRoot = getActivityRoot(activity);
//            if (activityRoot == null) {
//                return;
//            }
//            ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
//
//                private final Rect r = new Rect();
//                private final int visibleThreshold = Math.round(DensityUtils.dip2px(activity, KEYBOARD_VISIBLE_THRESHOLD_DP));
//
//                @Override
//                public void onGlobalLayout() {
//                    activityRoot.getWindowVisibleDisplayFrame(r);
//                    int heightDiff = activityRoot.getRootView().getHeight() - r.height();
//                    boolean isOpen = heightDiff > visibleThreshold;
//
//                    if (isOpen == wasOpened) {
//                        // keyboard state has not changed
//                        return;
//                    }
//                    wasOpened = isOpen;
//
//                    //发个事件
////                    EventBus.getDefault().post(new KeyboardVisibleEvent(isOpen));
//                }
//            };
//
//            activityRoot.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private View getActivityRoot(Activity activity) {

        final View activityRoot = activity.getWindow().getDecorView();
        if (activityRoot == null) {
            return null;
        }
        ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

            private final Rect r = new Rect();
            private final int visibleThreshold = Math.round(DensityUtils.dip2px(activity, 100));

            @Override
            public void onGlobalLayout() {
                activityRoot.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRoot.getRootView().getHeight() - r.height();
                //键盘是否弹出
                boolean isOpen = heightDiff > visibleThreshold;

                if (isOpen == wasOpened) {
                    // keyboard state has not changed
                    return;
                }
                wasOpened = isOpen;
            }
        };
        return activityRoot;
    }

    private boolean isRun = true;

    @Override
    public void onActivityStarted(Activity activity) {
        if (isRun) {
            isRun = false;
//            if (isAppForeground(activity)) {
//                String userName = SPUtils.getInstance().getString(AppConfig.Login.AUTO_USER_NAME, "");//保存账号
//                String password = SPUtils.getInstance().getString(AppConfig.Login.AUTO_PWD, "");//保存密码
//                if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
////                    mILoginPresenter.doLogin(activity, userName, password);
//                }
//            }
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
//        if (!isAppForeground(activity)) {
//            L.i("onActivityStopped");
//            isRun = true;
//        }
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
//        if (!isAppForeground(activity)) {
//            L.i("onActivityDestroyed");
//            isRun = true;
//        }
    }

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

    /**
     * 前後台切換判斷
     *
     * @param context
     * @return
     */
    private static boolean isAppForeground(Context context) {
        if (context != null) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processes;
            if (activityManager != null) {
                processes = activityManager.getRunningAppProcesses();
            } else {
                return false;
            }
            for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.processName.equals(context.getPackageName())) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
