package com.datarecovery.master.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.atmob.common.runtime.ActivityUtil;
import com.atmob.common.runtime.ContextUtil;
import com.atmob.mediation.api.AtmobAdSdk;
import com.datarecovery.master.module.splash.SplashActivity;

import java.util.Arrays;
import java.util.List;

public class SplashHandler {
    private static final String TAG = SplashHandler.class.getSimpleName();

    public static final int SplashRequestCode = 2843;

    private static final List<Class<? extends Activity>> WHITE_LIST = Arrays.asList(
            SplashActivity.class
    );

    private static boolean appInBackground = true;

    private static volatile boolean skipOnce;

    private SplashHandler() {

    }

    public static void init() {
        ProcessLifecycleOwner.get().getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
            if (event == Lifecycle.Event.ON_START) {
                appInBackground = false;
                showSplash();
            } else if (event == Lifecycle.Event.ON_STOP) {
                appInBackground = true;
            } else if (event == Lifecycle.Event.ON_DESTROY) {
            }
        });
    }

    public static boolean isAppInBackground() {
        return appInBackground;
    }

    private static void showSplash() {
        Activity topActivity = ActivityUtil.getTopActivity();
        if (topActivity == null) {
            Context context = ContextUtil.getContext();
            Intent intent = new Intent(context, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return;
        }
        if (couldShow(topActivity.getClass())) {
            Intent intent = new Intent(topActivity, SplashActivity.class);
            topActivity.startActivityForResult(intent, SplashRequestCode);
        }
    }

    private static boolean couldShow(Class<? extends Activity> activityClass) {
        if (skipOnce) {
            skipOnce = false;
            return false;
        }
        return !inWhiteList(activityClass);
    }

    public static boolean inWhiteList(Class<? extends Activity> activityClass) {
        return WHITE_LIST.contains(activityClass) || AtmobAdSdk.isAdActivity(activityClass);
    }

    public static void doNotShowNextTime() {
        skipOnce = true;
    }
}
