package ca.ksamad.encore.mpd.model

import ca.ksamad.encore.mpd.MpdResponse

/** An album in the library, optionally attributed to an album artist. */
data class MpdAlbum(
    val name: String,
    val albumArtist: String?,
) {
    companion object {
        /**
         * Parse the response of `list album group albumartist`. MPD emits an `AlbumArtist:` line
         * followed by the `Album:` lines belonging to it, so we track the current artist and attach
         * it to each album.
         */
        fun listFrom(response: MpdResponse): List<MpdAlbum> {
            val albums = ArrayList<MpdAlbum>()
            var currentArtist: String? = null
            for ((key, value) in response.values) {
                when (key) {
                    "AlbumArtist" -> currentArtist = value.ifEmpty { null }
                    "Album" -> if (value.isNotEmpty()) albums.add(MpdAlbum(value, currentArtist))
                }
            }
            return albums
        }
    }
}
