package com.dronex.rec.recording

import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.provider.Settings
import androidx.core.app.NotificationManagerCompat

object DoNotDisturbHelper {
    private var savedInterruptionFilter: Int? = null

    fun hasAccess(context: Context): Boolean {
        val manager = context.getSystemService(NotificationManager::class.java)
        return manager?.isNotificationPolicyAccessGranted == true
    }

    fun openAccessSettings(context: Context) {
        val intent =
                Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
        context.startActivity(intent)
    }

    fun enable(context: Context): Boolean {
        val manager = context.getSystemService(NotificationManager::class.java) ?: return false
        if (!manager.isNotificationPolicyAccessGranted) return false

        if (savedInterruptionFilter == null) {
            savedInterruptionFilter = manager.currentInterruptionFilter
        }
        manager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)
        return true
    }

    fun disable(context: Context) {
        val manager = context.getSystemService(NotificationManager::class.java) ?: return
        if (!manager.isNotificationPolicyAccessGranted) return

        val previous = savedInterruptionFilter ?: NotificationManager.INTERRUPTION_FILTER_ALL
        manager.setInterruptionFilter(previous)
        savedInterruptionFilter = null
    }

    fun areNotificationsEnabled(context: Context): Boolean {
        return NotificationManagerCompat.from(context).areNotificationsEnabled()
    }
}
