package invalid.lena.rsend

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

// SyncLog is a plain-text, append-only log of sync runs, capped in size. It is
// what the user reads to see what rsend did and to debug failures.
class SyncLog(ctx: Context) {

    val file: File = File(ctx.filesDir, "sync.log")
    private val fmt = SimpleDateFormat("MM-dd HH:mm:ss", Locale.US)

    fun line(s: String) {
        file.appendText("${fmt.format(Date())} $s\n")
    }

    // Truncate once the log grows past the cap so it cannot fill storage.
    fun rotateIfBig() {
        if (file.exists() && file.length() > 512 * 1024) file.writeText("")
    }

    fun text(): String = if (file.exists()) file.readText() else ""
}
