import Foundation

private typealias Replace = (orig: String, asName: String, asCode: String)
private let replaces = [
    Replace("&", "&amp;", "&#38;"),
    Replace("<", "&lt;", "&#60;"),
    Replace(">", "&gt;", "&#62;"),
    Replace("\"", "&quot;", "&#34;"),
    Replace("'", "&apos;", "&#39;")
]

enum XMLEscaping {
    static func unescape(_ value: String) -> String {
        if !value.contains("&") {
            return value
        }
        var result = value
        var indx = replaces.count-1
        while indx >= 0 {
            // this is for libxml2 as it replaces every &amp; with &#38; which in XML both replaces &
            result = result.replacingOccurrences(of: replaces[indx].asCode, with: replaces[indx].orig)

            // this is for normal replacement (may not be needed but let's keep it for compatibility
            result = result.replacingOccurrences(of: replaces[indx].asName, with: replaces[indx].orig)
            indx -= 1
        }
        return result
    }

    static func escape(_ value: String) -> String {
        var result = value
        var indx = 0
        while indx < replaces.count {
            result = result.replacingOccurrences(of: replaces[indx].orig, with: replaces[indx].asName)
            indx += 1
        }
        return result
    }
}
