package de.tsschulz.timeclock.data.offline

import android.content.Context
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import java.util.UUID

@Serializable
data class PendingClockAction(
    val id: String,
    val action: String,
    val createdAtEpochMillis: Long,
)

class OfflineClockQueue(
    context: Context,
    private val json: Json = Json { ignoreUnknownKeys = true },
) {
    private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    fun enqueue(action: String) {
        val next = pending() + PendingClockAction(
            id = UUID.randomUUID().toString(),
            action = action,
            createdAtEpochMillis = System.currentTimeMillis(),
        )
        save(next)
    }

    fun pending(): List<PendingClockAction> {
        val raw = prefs.getString(KEY_ACTIONS, null) ?: return emptyList()
        return runCatching {
            json.decodeFromString(ListSerializer(PendingClockAction.serializer()), raw)
        }.getOrDefault(emptyList())
    }

    fun remove(id: String) {
        save(pending().filterNot { it.id == id })
    }

    private fun save(actions: List<PendingClockAction>) {
        val raw = json.encodeToString(ListSerializer(PendingClockAction.serializer()), actions)
        prefs.edit().putString(KEY_ACTIONS, raw).apply()
    }

    private companion object {
        const val PREFS_NAME = "timeclock_offline_clock_queue"
        const val KEY_ACTIONS = "pending_clock_actions"
    }
}
