package mg.dot.feufaro.solfa

class TUNote (private val detailNote: MutableList<Note> = mutableListOf()){
    var prevTUNote: TUNote? = null
    var prevTUO: TimeUnitObject? = null
    var annotations: AnnotatedTUO? = null
    fun addNote(noteString: String) {
        val newNote = Note(noteString)
        detailNote.add(newNote)
    }
    fun from(note: Note?) {
        detailNote.add(note ?: Note(""))
    }
    fun addMarker(newMarker: Char, markerBefore: String = "" ) {
        if (newMarker == '0' && markerBefore == "") return
        val lastNote = detailNote.lastOrNull()
        if (lastNote == null) {
            val newNote = Note("")
            if (newMarker != '0') {
                newNote.addMarker(newMarker.toString())
            }
            if (markerBefore != "") {
                newNote.markBefore(markerBefore)
            }
            detailNote.add(newNote)
        } else {
            lastNote.addMarker(newMarker.toString())
            if (markerBefore != "") {
                lastNote.markBefore(markerBefore)
            }
        }
    }
    fun annotate(voiceNumber: Int) {
        val annotatedTUO = AnnotatedTUO(this.toString(), voiceNumber)
        annotations = if (annotatedTUO.underlineSpec.isNotEmpty()) {
            annotatedTUO
        } else {
            null
        }
    }
    override fun toString() : String {
        return toString("", "")
    }
    fun toString(fromKey: String = "", toKey: String = "") : String {
        var result = detailNote.joinToString (separator = ""){ it.toString() }
            .replace(Regex("^z\\.- ,[zw-]$"), "")
            .replace(Regex("\\. *,-$"), "")
            .replace(Regex(",-$"), "")
            .replace(Regex("(- *,z|- *,-|0$)"), "-")
            .replace(Regex("([^\\.,])-"), "$1")
            .replace(Regex("(?<=[drmfsltia]),,,"), "₃")
            .replace(Regex("(?<=[drmfsltia]),,"), "₂")
            .replace(Regex("(?<=[drmfsltia]),"), "₁")
            .replace("'''", "³")
            .replace("''", "²")
            .replace("'", "¹")
            .replace(Regex("[zZ][zZ\\.,]+(?![drmfslt])"), "")
            .replace(Regex("^-\\.,"), "")
            .replace(" ,z", "")
            .replace(Regex("^-.- *,"), "-. ,")
            .replace(Regex("(?<!,[drmfslt])\\.-\\s*$"), "")
            .replace(Regex(" ,-\\s*$"), "")
            .replace(Regex("\\((-[\\.,;][a-zA-Z][ia]*[¹²³₁₂₃]?)\\)"), "$1")
            .replace(Regex("^-\\.z$"), "")
            .replace("-", "―")
            .replace(".", "\u2022")
            .replace("z", "")
        if ((fromKey != "") && (toKey != "")) {
            result = ">" + Transpose.transposeToSolfa(result, fromKey, toKey) + ">" + result
        }
        return result
    }
}