package mg.dot.feufaro.solfa

class POneStanzaLyrics {
    private val lyrics: MutableList<String> = mutableListOf("")
    private val alternativeLyrics: MutableMap<Int, MutableMap<Int, String>> = mutableMapOf()
    fun getLyrics(stanzaNumber: Int) : String {
        return this.lyrics[stanzaNumber]
    }
    fun setLyrics(stanzaNumber: Int, lyrics: String) {
        while (this.lyrics.size <= stanzaNumber) {
            this.lyrics.add("")
        }
        this.lyrics[stanzaNumber] = lyrics.replace(Regex("\\$\\{[^\\}]*\\}-?"), "")
    }
    fun setAlternativeLyrics(stanzaNumber: Int, voiceNumber: Int, text: String) {
        alternativeLyrics
            .getOrPut(stanzaNumber) { mutableMapOf() } [voiceNumber] = text
    }
    fun copyAlternativeLyrics(fromStanzaNumber: Int, toStanzaNumber: Int) {
        val toCopy = this.alternativeLyrics[fromStanzaNumber]
        if (toCopy != null) {
            alternativeLyrics
                .getOrPut(toStanzaNumber) { toCopy }
        }
    }

    override fun toString(): String {
        val alternativeL = alternativeLyrics.values.flatMap { it.values }.joinToString("\n")
        if (alternativeL != "") { return lyrics[1]+"\n"+alternativeL }
        return lyrics[1]
    }
    fun appendDSLyrics(stanzaNumber: Int, lyrics: String) {
        if (this.lyrics.size > stanzaNumber) {
            this.lyrics[stanzaNumber] += "\n$lyrics"
        }
    }
    fun toList(stanzaNumber: Int): List<String> {
        val alternativeMap: MutableMap<Int, String>? = alternativeLyrics[stanzaNumber]
        val alternativeList: List<String> = alternativeMap?.values?.toList() ?: listOf()
        val result : MutableList<String> = if (this.lyrics.size > stanzaNumber) {
            this.lyrics[stanzaNumber].split("\n").toMutableList()
        } else
            mutableListOf()
        if (result.isNotEmpty() && alternativeList.isNotEmpty()) {
            result.addAll(1, alternativeList)   // overridedLyrics's index from 1 not 0
        } else {
            result.addAll(alternativeList)
        }
        return result
    }
}