package paymentutil

import (
	"bytes"
	"encoding/xml"
	"io"
	"sort"
	"strings"
)

type xmlValue struct {
	XMLName xml.Name
	Value   string `xml:",chardata"`
}

func XMLValues(raw []byte) (map[string]string, error) {
	decoder := xml.NewDecoder(bytes.NewReader(raw))
	result := map[string]string{}
	for {
		token, err := decoder.Token()
		if err == io.EOF {
			return result, nil
		}
		if err != nil {
			return nil, err
		}
		start, ok := token.(xml.StartElement)
		if !ok || start.Name.Local == "xml" {
			continue
		}
		var value xmlValue
		if err = decoder.DecodeElement(&value, &start); err != nil {
			return nil, err
		}
		if value.Value != "" {
			result[start.Name.Local] = value.Value
		}
	}
}

func XMLEncode(values map[string]string) []byte {
	var b strings.Builder
	b.WriteString("<xml>")
	keys := make([]string, 0, len(values))
	for key := range values {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, key := range keys {
		b.WriteString("<")
		b.WriteString(key)
		b.WriteString("><![CDATA[")
		b.WriteString(values[key])
		b.WriteString("]]></")
		b.WriteString(key)
		b.WriteString(">")
	}
	b.WriteString("</xml>")
	return []byte(b.String())
}
