package mg.dot.feufaro.solfa

class PMarkers(val code: String, val offset: Int = 0, var boundaries: Int = 0) {
    fun changeBoundaries(newBoundaries: Int) {
        boundaries = newBoundaries
    }
}
class PTemplate (val template: String, val separatorAfter: String, private val markers: MutableList<PMarkers> = mutableListOf()){
    var lastCalledMarker = 0
    fun resetCalledMarker() {
        lastCalledMarker = 0
    }
    fun hasMarker(marker: String): Boolean {
        return markers.any { it.code == marker }
    }
    fun callNextMarker(): PMarkers? {
        if (markers.size <= lastCalledMarker) return null
        val boundaries = if (markers.size > lastCalledMarker+1) {
            markers[lastCalledMarker+1].offset
        } else 0
        val pMarkers = markers[lastCalledMarker]
        lastCalledMarker++
        pMarkers.changeBoundaries(boundaries)
        return pMarkers
    }
    fun markerToString(): String {
        if (markers.isEmpty()) {
            return ""
        }
        return markers.joinToString(separator = "") {
            val prefix = if (it.offset <= 0) "" else " ".repeat(it.offset) //@todo better position the marker
            prefix + it.code.replace(Regex("^\\$\\{([abd-z]:)?(.*)\\}"), "$2")
                .replace("\$Q", "\uD834\uDD10")
                .replace(Regex("^[<=>]$"), "")
                .replace($$"$T", "")
                .replace(Regex("^c:(.*)"), "Do dia $1")
        }
    }
    fun hasKeyChange(): String {
        var returnFun = ""
        markers.map {
            val regexFound = Regex("^\\$\\{c:(..?)\\}").find(it.code)
            if (regexFound != null) {
                returnFun = regexFound.groupValues[1]
            }
            true
        }
        return returnFun
    }

}