package com.isidroid.utils

import android.app.NotificationChannel
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationManagerCompat

internal fun isNotificationChannelSupported() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O

fun Context.checkIfNotificationChannelExists(channelId: String): String? {
    if (!isNotificationChannelSupported()) return null

    val manager = NotificationManagerCompat.from(this)
    return manager.getNotificationChannel(channelId)?.id
}

fun Context.removeNotificationChannel(channelId: String?) {
    if (!isNotificationChannelSupported() || channelId.isNullOrBlank()) return

    val manager = NotificationManagerCompat.from(this)
    manager.deleteNotificationChannel(channelId)
}

fun Context.createNotificationChannel(
    channelId: String,
    name: String,
    importance: Int,
    description: String? = null,
    hasVibration: Boolean? = null,
    hasSound: Boolean = false,
) {
    if (!isNotificationChannelSupported()) return

    // check whether exists
    if (checkIfNotificationChannelExists(channelId) != null) return

    val channel = NotificationChannel(channelId, name, importance)
    description?.also { channel.description = it }
    hasVibration?.also { channel.enableVibration(it) }

    if (!hasSound)
        channel.setSound(null, null)

    NotificationManagerCompat.from(this).createNotificationChannel(channel)
}