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))
}
}
}