package com.seven.ikar.kotlin.ui

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.Window
import android.view.WindowManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import java.util.UUID

object SecureWindowFlagController {
    private val activeTokensByWindow = mutableMapOf<Int, MutableSet<String>>()

    fun setSecure(window: Window, token: String, enabled: Boolean) {
        synchronized(activeTokensByWindow) {
            val key = System.identityHashCode(window)
            val tokens = activeTokensByWindow.getOrPut(key) { mutableSetOf() }
            if (enabled) {
                tokens += token
            } else {
                tokens -= token
            }

            if (tokens.isEmpty()) {
                activeTokensByWindow -= key
                window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
            } else {
                window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
            }
        }
    }
}

@Composable
fun SecureWindowEffect(enabled: Boolean) {
    val view = LocalView.current
    val token = remember { UUID.randomUUID().toString() }

    DisposableEffect(view, enabled, token) {
        val window = view.context.findActivity()?.window
        if (window != null) {
            SecureWindowFlagController.setSecure(window, token, enabled)
        }

        onDispose {
            if (window != null) {
                SecureWindowFlagController.setSecure(window, token, false)
            }
        }
    }
}

private tailrec fun Context.findActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> null
}
