package xyz.dynamic.client.screenshot

import android.os.Handler
import android.os.Looper
import android.view.WindowManager
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.annotations.ReactModule
import xyz.dynamic.client.NativeScreenshotProtectionSpec

@ReactModule(name = ScreenshotProtectionModule.NAME)
class ScreenshotProtectionModule(reactContext: ReactApplicationContext) :
    NativeScreenshotProtectionSpec(reactContext) {

    companion object {
        const val NAME = "DynamicClientScreenshotProtection"
    }

    private val mainHandler = Handler(Looper.getMainLooper())

    // Whether *we* added FLAG_SECURE (via setEnabled(true)), so setEnabled(false)
    // only clears a flag we set and never a FLAG_SECURE the host app applied
    // itself. Main-thread-only (setEnabled posts to mainHandler).
    private var didAddSecureFlag = false

    override fun getName(): String = NAME

    // Window-level screenshot/recording protection. FLAG_SECURE is a property of
    // the Activity window (not any view), so this protects whatever is on screen
    // regardless of how it is rendered.
    override fun setEnabled(enabled: Boolean) {
        mainHandler.post {
            val window = reactApplicationContext.currentActivity?.window ?: return@post
            if (enabled) {
                // Only add (and remember) if not already set, so a later
                // setEnabled(false) never clears a FLAG_SECURE the host app set.
                val alreadySecure =
                    (window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) != 0
                if (!alreadySecure) {
                    window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
                    didAddSecureFlag = true
                }
            } else if (didAddSecureFlag) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
                didAddSecureFlag = false
            }
        }
    }
}
