package com.twm.tools.local

import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler

class ValuesStringSaxHandler: DefaultHandler() {

    private val values = mutableListOf<ValuesData>()
    private var pending: ValuesData? = null

    override fun startElement(uri: String?, localName: String?, qName: String?, attrs: Attributes?) {
        if (qName != "string") {
            pending = null
            return
        }
        val key = attrs?.getValue("name")
        if (key == null) {
            pending = null
        } else {
            pending = ValuesData(key)
        }
    }

    override fun endElement(uri: String?, localName: String?, qName: String?) {
        if (qName != "string") {
            pending = null
            return
        }
        if (pending != null) {
            values.add(pending!!)
            pending = null
        }
    }

    override fun characters(p0: CharArray, p1: Int, p2: Int) {
        if (pending != null) {
            pending?.value = String(p0, p1, p2)
        }
    }

    fun getCollectValues() = values as List<ValuesData>
}