package swiss.qpq.gajumobile.security

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class AppLifecycleObserver(private val context: Context) : DefaultLifecycleObserver {

    private var isRegistered = false

    private val screenOffReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == Intent.ACTION_SCREEN_OFF) {
                SecurityManager.lock()
            }
        }
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        SecurityManager.onAppForegrounded()
        if (!isRegistered) {
            context.registerReceiver(
                screenOffReceiver, 
                IntentFilter(Intent.ACTION_SCREEN_OFF),
                Context.RECEIVER_NOT_EXPORTED
            )
            isRegistered = true
        }
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        SecurityManager.onAppBackgrounded()
        if (isRegistered) {
            try {
                context.unregisterReceiver(screenOffReceiver)
            } catch (e: Exception) {
                android.util.Log.e("AppLifecycle", "Unregister failed", e)
            }
            isRegistered = false
        }
    }
}
