ChargingSnapshot.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.widget

import android.content.Context
import fr.codetics.evapp.core.JsonCoding
import fr.codetics.evapp.models.AppPrincipal
import fr.codetics.evapp.models.ChargingSessionResponse
import fr.codetics.evapp.models.InstantSerializer
import java.time.Instant
import kotlinx.serialization.Serializable

/** The last charging state the app saw, drawn by the home screen widget. */
@Serializable
data class ChargingSnapshot(
    val status: Status,
    val transactionId: Int? = null,
    val stationName: String? = null,
    val connectorId: Int? = null,
    @Serializable(with = InstantSerializer::class) val startedAt: Instant? = null,
    val energyKwh: Double? = null,
    val powerKw: Double? = null,
    val stateOfCharge: Int? = null,
    val price: Double? = null,
    val currency: String? = null,
    @Serializable(with = InstantSerializer::class) val updatedAt: Instant = Instant.now(),
) {
    enum class Status {
        SignedOut,
        Idle,
        Charging,
    }

    /** Same charge, same figures: the widget would draw the same thing. */
    fun looksLike(other: ChargingSnapshot?) = other != null && copy(updatedAt = Instant.EPOCH) == other.copy(updatedAt = Instant.EPOCH)

    companion object {
        fun from(
            principal: AppPrincipal?,
            sessions: List<ChargingSessionResponse>,
            stationName: (String) -> String?,
            now: Instant = Instant.now(),
        ): ChargingSnapshot {
            principal ?: return ChargingSnapshot(Status.SignedOut, updatedAt = now)
            val session =
                sessions.firstOrNull { it.stoppedAt == null && it.userId == principal.id }
                    ?: return ChargingSnapshot(Status.Idle, updatedAt = now)
            return ChargingSnapshot(
                status = Status.Charging,
                transactionId = session.id,
                stationName = stationName(session.stationId) ?: session.stationId,
                connectorId = session.connectorId,
                startedAt = session.startedAt,
                energyKwh = session.energyKwh,
                powerKw = session.currentPowerKw,
                stateOfCharge = session.stateOfCharge,
                price = session.price?.toDouble(),
                currency = session.currency,
                updatedAt = now,
            )
        }
    }
}

class WidgetSnapshotStore(context: Context) {
    private val preferences = context.getSharedPreferences("widget", Context.MODE_PRIVATE)

    fun load(): ChargingSnapshot? =
        preferences.getString(KEY, null)?.let { runCatching { JsonCoding.json.decodeFromString(ChargingSnapshot.serializer(), it) }.getOrNull() }

    fun save(snapshot: ChargingSnapshot) {
        preferences.edit().putString(KEY, JsonCoding.json.encodeToString(ChargingSnapshot.serializer(), snapshot)).apply()
    }

    private companion object {
        const val KEY = "charging.snapshot"
    }
}