Pith - timber
package com.vgmlr.timber

import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document as Doc
import android.provider.MediaStore
import android.provider.MediaStore.MediaColumns as Col
import androidx.core.net.toUri

internal data class TimberClip(
    val uri: Uri,
    val id: Int,
    val name: String,
    val size: Long,
    val length: Long,
    val stamp: Long
) {
    val key: String get() = uri.toString()
    val base: String get() = name.substringBeforeLast('.')
    val ext: String get() = name.substringAfterLast('.', "")
}

private class Raw(val uri: Uri, val name: String, val size: Long, val stamp: Long, val length: Long)

internal object TimberStore {
    private val MEDIA_PATH = if (Build.VERSION.SDK_INT >= 31) "Recordings/" else "Music/Recordings/"
    private val lengths = HashMap<String, Long>()

    private fun media(): Uri = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

    private fun isMedia(uri: Uri) = uri.authority == MediaStore.AUTHORITY

    private fun treeDoc(tree: Uri): Uri =
        DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))

    fun mime(ext: String) = if (ext == FMT_WAV) "audio/x-wav" else "audio/mp4"

    fun list(ctx: Context): List<TimberClip> {
        val dir = TimberPrefs(ctx).dir
        val raw = runCatching {
            if (dir.isEmpty()) fromMedia(ctx) else fromTree(ctx, dir.toUri())
        }.getOrDefault(emptyList())
        val ids = assign(ctx, raw.sortedBy { it.stamp }.map { it.uri.toString() })
        return raw.map {
            TimberClip(it.uri, ids.getValue(it.uri.toString()), it.name, it.size, it.length, it.stamp)
        }
    }

    private fun fromMedia(ctx: Context): List<Raw> {
        val cols = arrayOf(Col._ID, Col.DISPLAY_NAME, Col.SIZE, Col.DATE_MODIFIED, Col.DURATION)
        val out = ArrayList<Raw>()
        ctx.contentResolver.query(
            media(), cols, "${Col.RELATIVE_PATH} = ?", arrayOf(MEDIA_PATH), null
        )?.use { c ->
            while (c.moveToNext()) {
                val name = c.getString(1) ?: continue
                val uri = ContentUris.withAppendedId(media(), c.getLong(0))
                val size = c.getLong(2)
                val stamp = c.getLong(3) * 1000
                val len = c.getLong(4).takeIf { it > 0 } ?: length(ctx, uri, size, stamp)
                out += Raw(uri, name, size, stamp, len)
            }
        }
        return out
    }

    private fun fromTree(ctx: Context, tree: Uri): List<Raw> {
        val kids = DocumentsContract.buildChildDocumentsUriUsingTree(
            tree, DocumentsContract.getTreeDocumentId(tree)
        )
        val cols = arrayOf(
            Doc.COLUMN_DOCUMENT_ID,
            Doc.COLUMN_DISPLAY_NAME,
            Doc.COLUMN_SIZE,
            Doc.COLUMN_LAST_MODIFIED,
            Doc.COLUMN_MIME_TYPE
        )
        val out = ArrayList<Raw>()
        ctx.contentResolver.query(kids, cols, null, null, null)?.use { c ->
            while (c.moveToNext()) {
                val type = c.getString(4) ?: ""
                if (!type.startsWith("audio/")) continue
                val name = c.getString(1) ?: continue
                val uri = DocumentsContract.buildDocumentUriUsingTree(tree, c.getString(0))
                val size = c.getLong(2)
                val stamp = c.getLong(3)
                out += Raw(uri, name, size, stamp, length(ctx, uri, size, stamp))
            }
        }
        return out
    }

    private fun length(ctx: Context, uri: Uri, size: Long, stamp: Long): Long {
        val k = "$uri|$size|$stamp"
        synchronized(lengths) { lengths[k]?.let { return it } }
        val ms = runCatching {
            val r = MediaMetadataRetriever()
            try {
                r.setDataSource(ctx, uri)
                r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
            } finally {
                r.release()
            }
        }.getOrDefault(0L)
        synchronized(lengths) { lengths[k] = ms }
        return ms
    }

    @Synchronized
    private fun assign(ctx: Context, keys: List<String>): Map<String, Int> {
        val p = TimberPrefs(ctx)
        val ids = p.ids()
        var next = p.nextId
        var dirty = false
        keys.forEach {
            if (it !in ids) {
                ids[it] = next++
                dirty = true
            }
        }
        if (dirty) p.saveIds(ids, next)
        return ids
    }

    @Synchronized
    fun claim(ctx: Context, uri: Uri): Int =
        assign(ctx, listOf(uri.toString())).getValue(uri.toString())

    @Synchronized
    private fun rekey(ctx: Context, old: String, new: String?) {
        val p = TimberPrefs(ctx)
        val ids = p.ids()
        val id = ids.remove(old)
        if (new != null && id != null) ids[new] = id
        p.saveIds(ids, p.nextId)
    }

    fun create(ctx: Context, name: String, mime: String): Uri? = runCatching {
        val dir = TimberPrefs(ctx).dir
        if (dir.isEmpty()) {
            val v = ContentValues().apply {
                put(Col.DISPLAY_NAME, name)
                put(Col.MIME_TYPE, mime)
                put(Col.RELATIVE_PATH, MEDIA_PATH)
                put(Col.IS_PENDING, 1)
            }
            ctx.contentResolver.insert(media(), v)
        } else {
            DocumentsContract.createDocument(ctx.contentResolver, treeDoc(dir.toUri()), mime, name)
        }
    }.getOrNull()

    fun publish(ctx: Context, uri: Uri) {
        if (!isMedia(uri)) return
        runCatching {
            ctx.contentResolver.update(uri, ContentValues().apply { put(Col.IS_PENDING, 0) }, null, null)
        }
    }

    fun rename(ctx: Context, clip: TimberClip, name: String): Boolean = runCatching {
        if (isMedia(clip.uri)) {
            ctx.contentResolver.update(
                clip.uri, ContentValues().apply { put(Col.DISPLAY_NAME, name) }, null, null
            ) > 0
        } else {
            val moved = DocumentsContract.renameDocument(ctx.contentResolver, clip.uri, name)
                ?: return@runCatching false
            rekey(ctx, clip.key, moved.toString())
            true
        }
    }.getOrDefault(false)

    fun delete(ctx: Context, uri: Uri): Boolean {
        val ok = runCatching {
            if (isMedia(uri)) ctx.contentResolver.delete(uri, null, null) > 0
            else DocumentsContract.deleteDocument(ctx.contentResolver, uri)
        }.getOrDefault(false)
        if (ok) rekey(ctx, uri.toString(), null)
        return ok
    }

    fun dirName(ctx: Context): String {
        val dir = TimberPrefs(ctx).dir
        if (dir.isEmpty()) return DIR_DEFAULT
        return runCatching {
            ctx.contentResolver.query(
                treeDoc(dir.toUri()), arrayOf(Doc.COLUMN_DISPLAY_NAME), null, null, null
            )?.use { if (it.moveToFirst()) it.getString(0) else null }
        }.getOrNull() ?: dir
    }
}