Pith - jamb
jamb/app/src/main/java/com/vgmlr/jamb/JambPlaylists.kt [2.2 kb]
Modified: 20:33:38 112 026 (09 Jul 026)
16 Days Ago
package com.vgmlr.jamb

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first

private val Context.playlistStore by preferencesDataStore("jamb_playlists")

class JambPlaylists(private val context: Context) {

    companion object {
        private val NAMES = stringPreferencesKey("names")
        private const val SEP = "\n"
        private fun itemsKey(name: String) = stringPreferencesKey("pl:$name")
    }

    private fun decode(s: String?): List<String> =
        s?.split(SEP)?.filter { it.isNotEmpty() } ?: emptyList()

    private fun encode(list: List<String>): String = list.joinToString(SEP)

    suspend fun names(): List<String> =
        decode(context.playlistStore.data.first()[NAMES])

    suspend fun items(name: String): List<String> =
        decode(context.playlistStore.data.first()[itemsKey(name)])

    suspend fun create(name: String) {
        context.playlistStore.edit { p ->
            val cur = decode(p[NAMES])
            if (!cur.contains(name)) p[NAMES] = encode(cur + name)
            if (p[itemsKey(name)] == null) p[itemsKey(name)] = ""
        }
    }

    suspend fun add(name: String, file: String) {
        context.playlistStore.edit { p ->
            val items = decode(p[itemsKey(name)])
            if (!items.contains(file)) p[itemsKey(name)] = encode(items + file)
        }
    }

    suspend fun remove(name: String, file: String) {
        context.playlistStore.edit { p ->
            p[itemsKey(name)] = encode(decode(p[itemsKey(name)]) - file)
        }
    }

    suspend fun delete(name: String) {
        context.playlistStore.edit { p ->
            p[NAMES] = encode(decode(p[NAMES]) - name)
            p.remove(itemsKey(name))
        }
    }

    suspend fun rename(from: String, to: String) {
        context.playlistStore.edit { p ->
            if (decode(p[NAMES]).contains(to)) return@edit
            p[NAMES] = encode(decode(p[NAMES]).map { if (it == from) to else it })
            p[itemsKey(to)] = p[itemsKey(from)] ?: ""
            p.remove(itemsKey(from))
        }
    }
}
Updates
Wedge - Android 126.026
Wedge - Linux 124.026
Shim - Android 117.026
Miter - 114.026
Kerf - Android 112.026
Dev
TVShow (227) 'CSA'
TVShow (228) 'APT'
TVProgram (83) 'BXT'
Miter Update(s)
Peen (Messaging)

Menu
Calendar
Project Tin (024/029)
Miter
RSS Feed
User Avatar
@vgmlr
=SUM(parts)