LiveUpdateNotifier.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.evapp.push

import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import fr.codetics.evapp.EvApp
import fr.codetics.evapp.MainActivity
import fr.codetics.evapp.R
import fr.codetics.evapp.core.Formatters
import java.math.BigDecimal

/** A charging session as sent by the server in a live update (`AndroidLiveUpdateService`). */
data class LiveSession(
    val transactionId: Int,
    val stationName: String,
    val connectorId: Int,
    val startedAtSeconds: Long,
    val energyKwh: Double?,
    val powerKw: Double?,
    val stateOfCharge: Int?,
    val price: BigDecimal?,
    val currency: String?,
    val finished: Boolean,
) {
    companion object {
        const val TYPE_UPDATE = "session_live_update"
        const val TYPE_ENDED = "session_live_ended"

        /** Reads an FCM data message; null when it is not a live update. */
        fun from(data: Map<String, String>): LiveSession? {
            val type = data["type"]
            if (type != TYPE_UPDATE && type != TYPE_ENDED) return null
            val transaction = data["transaction_id"]?.toIntOrNull() ?: return null
            return LiveSession(
                transactionId = transaction,
                stationName = data["station_name"].orEmpty(),
                connectorId = data["connector_id"]?.toIntOrNull() ?: 0,
                startedAtSeconds = data["started_at"]?.toLongOrNull() ?: 0,
                energyKwh = data["energy_kwh"]?.toDoubleOrNull(),
                powerKw = data["power_kw"]?.toDoubleOrNull(),
                stateOfCharge = data["state_of_charge"]?.toIntOrNull()?.coerceIn(0, 100),
                price = data["price"]?.toBigDecimalOrNull(),
                currency = data["currency"],
                finished = type == TYPE_ENDED,
            )
        }
    }
}

/**
 * Shows a running session as an ongoing notification, the Android counterpart of the iOS Live Activity.
 * On Android 16 it asks to be promoted to a Live Update (status bar chip, lock screen); older versions
 * show a regular ongoing notification. The session's end replaces it with a summary the driver can dismiss.
 */
class LiveUpdateNotifier(private val context: Context) {
    fun show(session: LiveSession) {
        val manager = NotificationManagerCompat.from(context)
        if (!manager.areNotificationsEnabled()) return
        val id = NOTIFICATION_BASE + session.transactionId
        runCatching { manager.notify(TAG, id, build(session)) }
    }

    fun build(session: LiveSession): Notification {
        val details =
            listOfNotNull(
                    Formatters.energy(session.energyKwh),
                    session.powerKw?.takeIf { !session.finished }?.let(Formatters::power),
                    session.price?.let { Formatters.price(it, session.currency) },
                )
                .joinToString(" · ")
        val builder =
            NotificationCompat.Builder(context, EvApp.CHANNEL_CHARGING_LIVE)
                .setSmallIcon(R.drawable.sym_ev_station_fill)
                .setContentTitle(
                    context.getString(
                        if (session.finished) R.string.live_update_finished else R.string.live_update_charging,
                        session.stationName,
                    )
                )
                .setContentText(details)
                .setContentIntent(open(session))
                .setCategory(NotificationCompat.CATEGORY_PROGRESS)
                .setOnlyAlertOnce(true)
                .setSilent(!session.finished)
        if (session.finished) {
            builder.setOngoing(false).setAutoCancel(true).setTimeoutAfter(FINISHED_TIMEOUT)
        } else {
            builder
                .setOngoing(true)
                .setRequestPromotedOngoing(true)
                .setUsesChronometer(session.startedAtSeconds > 0)
                .setWhen(session.startedAtSeconds * 1000)
                .setShortCriticalText(session.stateOfCharge?.let { "$it %" } ?: Formatters.energy(session.energyKwh))
            val charge = session.stateOfCharge
            if (charge != null) {
                builder.setStyle(
                    NotificationCompat.ProgressStyle()
                        .setProgress(charge)
                        .setProgressSegments(listOf(NotificationCompat.ProgressStyle.Segment(100)))
                )
            } else {
                builder.setProgress(0, 0, true)
            }
        }
        return builder.build()
    }

    private fun open(session: LiveSession): PendingIntent =
        PendingIntent.getActivity(
            context,
            session.transactionId,
            Intent(context, MainActivity::class.java)
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .putExtra("transaction_id", session.transactionId.toString()),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
        )

    private companion object {
        const val TAG = "live-session"
        const val NOTIFICATION_BASE = 0
        const val FINISHED_TIMEOUT = 30 * 60 * 1000L
    }
}