package com.nielsen.simplenoidandroidart.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.nielsen.app.sdk.AppLaunchMeasurementManager;

/**
 * Created by abdul on 07/03/18.
 */

public class SdkBgFgDetectionUtility {
    //Instance of Application class
    private Application app = null;

    /**
     * Constructor for SdkLifeCycleUtility
     * @param appInstance : Instance of Application. This parameter should not be null.
     */
    public SdkBgFgDetectionUtility(Application appInstance){
        this.app = appInstance;
    }

    /**
     * Function to start handling app life cycle events like app background and foreground etc.
     *
     */
    @TargetApi(14)
    public void handleSdkLifecycleEvents(){


        if(Build.VERSION.SDK_INT >= 14 && this.app != null) {
            this.app.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                private int b = 0;

                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }

                public void onActivityDestroyed(Activity activity) {
                }

                public void onActivityPaused(Activity activity) {
                }

                public void onActivityStarted(Activity activity) {
                    if(this.b == 0) {
                        AppLaunchMeasurementManager.appInForeground(app.getApplicationContext());
                        Log.d("SdkBgFgDetectionUtility", "App running in foreground");
                        ++this.b;
                    } else if(this.b > 0) {
                        ++this.b;
                    }

                }

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

                public void onActivityResumed(Activity activity) {
                }

                public void onActivityStopped(Activity activity) {
                    --this.b;
                    if(this.b == 0) {
                        AppLaunchMeasurementManager.appInBackground(app.getApplicationContext());
                        Log.d("SdkBgFgDetectionUtility", "App going to background");
                    }

                }
            });
        } else {
            Log.w("SdkBgFgDetectionUtility", "Cannot detect background/foreground states automatically as the android version is below ICS(API Level 14)");
        }
    }
}
