package com.iscs.bozzys.ui.pages.compose

import android.Manifest
import android.content.Context
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.NotificationManagerCompat
import com.iscs.bozzys.utils.LogUtil

/**
 * 校验通知是否使能
 */
fun Context.isNotificationEnabled(): Boolean {
    return NotificationManagerCompat.from(this).areNotificationsEnabled()
}

/**
 * 通知权限申请
 */
@Composable
fun RequestNotificationPermission() {
    val ctx = LocalContext.current
    val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) {
            LogUtil.d("NotificationPermission", "允许通知")
        } else {
            LogUtil.d("NotificationPermission", "拒绝通知")
        }
    }
    // 执行通知权限的申请
    LaunchedEffect(Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (!ctx.isNotificationEnabled()) {
                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
}