package invalid.lena.rsend

import android.content.Context
import android.util.AtomicFile
import java.io.File
import java.io.FileNotFoundException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

// LastSync records the outcome of the most recent run so the dashboard can show
// it without opening the log. This small status is independent of the full log.
object LastSync {

    private const val MAX_STATUS_CHARS = 4_000
    private const val MAX_FILE_BYTES = 20 * 1024

    private fun file(ctx: Context): File = File(ctx.filesDir, "last-sync")

    @Synchronized
    fun set(ctx: Context, status: String) {
        val clean = buildString(minOf(status.length, MAX_STATUS_CHARS)) {
            for (c in status) {
                append(if (c.isISOControl()) ' ' else c)
                if (length == MAX_STATUS_CHARS) break
            }
        }
        val time = SimpleDateFormat("MM-dd HH:mm", Locale.US).format(Date())
        val file = AtomicFile(file(ctx))
        val out = file.startWrite()
        try {
            out.write("$time $clean".toByteArray(Charsets.UTF_8))
            file.finishWrite(out)
        } catch (e: Exception) {
            file.failWrite(out)
            throw e
        }
    }

    @Synchronized
    fun get(ctx: Context): String = try {
        AtomicFile(file(ctx)).openRead().use { Config.readText(it, MAX_FILE_BYTES) }
    } catch (_: FileNotFoundException) {
        "never"
    } catch (e: Exception) {
        "unavailable (${e.javaClass.simpleName})"
    }
}
