package com.applemand.zmanim.core.notifications

import android.Manifest
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat

/**
 * Receives exact-alarm triggers for candle lighting, havdalah, fast start/end, etc.
 * Intent extras:
 *   KEY_TITLE  : notification title
 *   KEY_TEXT   : notification body
 *   KEY_ID     : stable int id
 */
class ZmanimAlarmReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val title = intent.getStringExtra(KEY_TITLE) ?: return
        val text = intent.getStringExtra(KEY_TEXT) ?: ""
        val id = intent.getIntExtra(KEY_ID, 0)

        if (ContextCompat.checkSelfPermission(
                context, Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) return

        Channels.ensure(context)

        val tap = Intent(Intent.ACTION_VIEW, android.net.Uri.parse("luach://day"))
            .setPackage(context.packageName)
        val pi = PendingIntent.getActivity(
            context, id, tap,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        val n = NotificationCompat.Builder(context, Channels.CHANNEL_ZMANIM)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle(title)
            .setContentText(text)
            .setStyle(NotificationCompat.BigTextStyle().bigText(text))
            .setContentIntent(pi)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        NotificationManagerCompat.from(context).notify(id, n)
    }

    companion object {
        const val KEY_TITLE = "title"
        const val KEY_TEXT = "text"
        const val KEY_ID = "id"
    }
}
