package xyz.myachin.saveto.ui.notification

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import xyz.myachin.saveto.R

class ResetDefaultsNotification(private val context: Context) {
    private val manager =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    private val notificationChannel by lazy {
        NotificationChannelCompat.Builder(REMOVE_DEFAULT_NOTIFICATION_CHANNEL_ID,
            NotificationManagerCompat.IMPORTANCE_DEFAULT)
            .setName(context.getString(R.string.prevent_be_default_action_view))
            .build()
    }

    private val settingsAction: String
        get() {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS
            } else {
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            }
        }

    private val settingsIntent: PendingIntent by lazy {
        PendingIntent.getActivity(context.applicationContext,
            REMOVE_DEFAULT_REQUEST_CODE,
            Intent(settingsAction).apply {
                data = Uri.fromParts("package", context.applicationContext.packageName, "")
            }, PendingIntent.FLAG_IMMUTABLE)
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            manager
                .createNotificationChannel(NotificationChannel(
                    notificationChannel.id,
                    notificationChannel.name,
                    notificationChannel.importance))
        }
    }

    fun reset() {
        manager.activeNotifications.forEach { if (it.id == REMOVE_DEFAULT_REQUEST_CODE) return }

        NotificationManagerCompat.from(context.applicationContext)
            .notify(REMOVE_DEFAULT_REQUEST_CODE, NotificationCompat
                .Builder(context.applicationContext, REMOVE_DEFAULT_NOTIFICATION_CHANNEL_ID)
                .setContentIntent(settingsIntent)
                .setContentTitle(context.applicationContext.getString(R.string.clear_defaults))
                .setContentText(context.getText(R.string.need_to_reset_defaults))
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources,
                    R.mipmap.ic_launcher_round))
                .setAutoCancel(true)
                .build())
    }
}