WidgetBridge.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 androidx.glance.appwidget.updateAll
import fr.codetics.evapp.models.AppPrincipal
import fr.codetics.evapp.models.ChargingSessionResponse
import java.time.Duration
import java.time.Instant
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/** Shares the charging state with the home screen widget and redraws it when it changes. */
class WidgetBridge(private val context: Context, private val scope: CoroutineScope) {
    private val store = WidgetSnapshotStore(context)
    private var lastUpdate = Instant.EPOCH

    fun publish(principal: AppPrincipal?, sessions: List<ChargingSessionResponse>, stationName: (String) -> String?) {
        val snapshot = ChargingSnapshot.from(principal, sessions, stationName)
        val previous = store.load()
        store.save(snapshot)
        val changedState = previous?.status != snapshot.status || previous.transactionId != snapshot.transactionId
        val changedFigures = !snapshot.looksLike(previous)
        if (!changedState && !(changedFigures && Duration.between(lastUpdate, Instant.now()) > REDRAW_INTERVAL)) return
        lastUpdate = Instant.now()
        scope.launch { runCatching { ChargingWidget().updateAll(context) } }
    }

    private companion object {
        val REDRAW_INTERVAL: Duration = Duration.ofSeconds(60)
    }
}