package com.base.pdfreaderallpdfreader.fcm;


import static com.base.pdfreaderallpdfreader.fcm.PopupConstObject.lockS;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;


import com.base.pdfreaderallpdfreader.utils.AppPreferences;
import com.base.pdfreaderallpdfreader.utils.LogEx;

import java.util.Objects;


public class ScreenStatusReceiver extends BroadcastReceiver {

    private static boolean isDeviceInteractive = true;
    private static boolean isSecureLockActive = false;

    public static void setupScreenStatusListener(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_USER_PRESENT);

        final Context applicationContext = context.getApplicationContext();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            applicationContext.registerReceiver(new ScreenStatusReceiver(), intentFilter, Context.RECEIVER_EXPORTED);
        } else {
            applicationContext.registerReceiver(new ScreenStatusReceiver(), intentFilter);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (Objects.requireNonNull(action)) {
            case Intent.ACTION_SCREEN_ON:
                setDeviceInteractive(true);
                break;
            case Intent.ACTION_SCREEN_OFF:
                setDeviceInteractive(false);
                setSecureLockActive(true);
                break;
            case Intent.ACTION_USER_PRESENT:
                LogEx.INSTANCE.logDebug("ScreenStatusReceiver", "ACTION_USER_PRESENT", false);
                setSecureLockActive(false);
                if (isDeviceInteractive() && !isSecureLockActive()) {
                    int secureSetting = Integer.parseInt(AppPreferences.getInstance().getString(lockS, "1"));
                    if (secureSetting == 1) {
                        String actionId = NotificationUiUtil.INSTANCE.getNextActionId();
                        NotificationUiUtil.INSTANCE.sendNotificationIfCan(context, actionId, PopupConstObject.POPUP_WHERE_LOCK);
                    }
                }
                break;
        }
    }

    private void setDeviceInteractive(boolean interactive) {
        isDeviceInteractive = interactive;
    }

    public static boolean isDeviceInteractive() {
        return isDeviceInteractive;
    }

    private void setSecureLockActive(boolean active) {
        isSecureLockActive = active;
    }

    public static boolean isSecureLockActive() {
        return isSecureLockActive;
    }
}