package com.humand.demo.modules.FullScreenNotificationPermission
import android.app.AlertDialog
import android.app.NotificationManager
import android.content.Intent
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.humand.demo.R

class FullScreenNotificationPermissionModule(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "FullScreenNotificationPermissionModule"
    }

    @ReactMethod
    fun requestIfNeeded(promise: Promise) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            val notificationManager = reactContext.getSystemService(NotificationManager::class.java)
            if (!notificationManager.canUseFullScreenIntent()) {
                val context = reactContext.currentActivity ?: reactContext

                AlertDialog.Builder(context)
                    .setTitle(R.string.full_screen_notification_permission_title)
                    .setMessage(R.string.full_screen_notification_permission_description)
                    .setPositiveButton(R.string.enable) { _, _ ->
                        val intent = Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT).apply {
                            data = Uri.parse("package:${reactContext.packageName}")
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        }
                        context.startActivity(intent)
                        promise.resolve("granted")
                    }
                    .setNegativeButton(R.string.cancel) { _, _ ->
                        promise.resolve("denied")
                    }
                    .show()
            } else {
                promise.resolve("already_granted")
            }
        } else {
            promise.resolve("not_applicable")
        }
    }
}
