package `in`.caresoft.carepulse.connect.data import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import org.json.JSONObject /** * Offline-first queue: every batch from a device is stored here first and uploaded by UploadWorker. * Nothing is lost if the phone has no network; the server de-duplicates on (device, parameter, time). */ class ReadingQueue(ctx: Context) : SQLiteOpenHelper(ctx, "queue.db", null, 1) { override fun onCreate(db: SQLiteDatabase) { db.execSQL("CREATE TABLE q (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, created INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, summary TEXT)") db.execSQL("CREATE TABLE history (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, text TEXT NOT NULL, flag TEXT)") } override fun onUpgrade(db: SQLiteDatabase, oldV: Int, newV: Int) {} fun add(batch: JSONObject, summary: String) { writableDatabase.insert("q", null, ContentValues().apply { put("body", batch.toString()); put("created", System.currentTimeMillis()); put("summary", summary) }) } /** Up to [limit] oldest batches: id to JSON. */ fun peek(limit: Int = 100): List> = readableDatabase.rawQuery("SELECT id, body FROM q ORDER BY id LIMIT $limit", null).use { c -> buildList { while (c.moveToNext()) add(c.getLong(0) to JSONObject(c.getString(1))) } } fun remove(ids: List) { if (ids.isNotEmpty()) writableDatabase.execSQL("DELETE FROM q WHERE id IN (${ids.joinToString(",")})") } fun bump(ids: List) { if (ids.isNotEmpty()) writableDatabase.execSQL("UPDATE q SET attempts = attempts + 1 WHERE id IN (${ids.joinToString(",")})") } fun count(): Int = readableDatabase.rawQuery("SELECT COUNT(*) FROM q", null).use { it.moveToFirst(); it.getInt(0) } fun log(text: String, flag: String? = null) { writableDatabase.insert("history", null, ContentValues().apply { put("at", System.currentTimeMillis()); put("text", text); put("flag", flag) }) writableDatabase.execSQL("DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT 200)") } fun history(limit: Int = 50): List> = readableDatabase.rawQuery("SELECT at, text, flag FROM history ORDER BY id DESC LIMIT $limit", null).use { c -> buildList { while (c.moveToNext()) add(Triple(c.getLong(0), c.getString(1), c.getString(2))) } } }