package com.sambath.kunkhmer.util;

import android.app.ActivityManager;
import android.content.Context;
import android.os.AsyncTask;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import timber.log.Timber;

/**
 * If some screen don't use Auto Logout, just don't observe live data and cancel Timer on resume in it
 */
public class LogOutTimerUtil {

    public interface LogOutListener {
        void doLogout();
    }

    public static final MutableLiveData<Boolean> isUserTimedOutLiveData = new MutableLiveData<>(false);
    public static Boolean isUserTimedOut = false;

    static Timer longTimer;

    public static synchronized void resetLogoutTimer(final Context context, final LogOutListener logOutListener) {
        cancelTimer();
        longTimer = new Timer();
        longTimer.schedule(new TimerTask() {
            public void run() {
                cancel();
                longTimer = null;
                try {
                    /*boolean foreGround = new ForegroundCheckTask().execute(context).get();
                    if (foreGround) {
                        logOutListener.doLogout();
                    } else {
                        isUserTimedOut = true;
                    }*/
                    isUserTimedOutLiveData.postValue(true);
                } catch (Exception e) {
                    Timber.d(e);
                }
            }
        }, Const.LOGOUT_TIME);
    }

    public static synchronized void cancelTimer () {
        if (longTimer != null) {
            longTimer.cancel();
            longTimer = null;
        }
    }

    static class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Context... params) {
            final Context context = params[0].getApplicationContext();
            return isAppOnForeground(context);
        }

        private boolean isAppOnForeground(Context context) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
            if (appProcesses == null) {
                return false;
            }
            final String packageName = context.getPackageName();
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                    return true;
                }
            }
            return false;
        }
    }

}