package com.base.browserwhite.fcm;

import static com.base.browserwhite.fcm.NotificationPushUtil.PUSH_WHERE_UNLOCK;

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

import com.base.browserwhite.utils.AppPreferences;

import java.util.Objects;


public class ScreenStatusReceiver extends BroadcastReceiver {

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

    static boolean haveRegister = false;

    public static void setupScreenStatusListener(Context context) {
        if (haveRegister) return;
        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);
        }
        haveRegister = true;
    }

    @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:
                setSecureLockActive(false);
                if (isDeviceInteractive() && !isSecureLockActive()) {
                    int secureSetting = Integer.parseInt(AppPreferences.getInstance().getString("lockS", "1"));
                    if (secureSetting == 1) {
                        Log.d("glc", "lockS");
                        NotificationPushUtil.INSTANCE.sendNotificationWhere(context, null, PUSH_WHERE_UNLOCK);
                    }
                }
                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;
    }
}