package com.srbenoit.xml;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.TreeMap;

/**
 * The base class for XML elements.
 */
public class ElementBase extends TreeMap<String, String> {

    /** version number for serialization */
    private static final long serialVersionUID = -5830831427588246195L;

    /** the line end character */
    protected static final String CRLF;

    /** the character encoding to use for URL encode/decode */
    protected static final String UTF8 = "UTF-8";

    /** the parsed tag name */
    public final transient String tagName;

    static {
        String crlf;

        crlf = System.getProperty("line.separator");
        CRLF = (crlf == null) ? "\r\n" : crlf;
    }

    /**
     * Constructs a new <code>AbstractElement</code>.
     *
     * @param  tag  the parsed tag name
     */
    public ElementBase(final String tag) {

        super();

        this.tagName = tag;
    }

    /**
     * Encode a string for inclusion in XML.
     *
     * @param   str  the string to encode
     * @return  the encoded string
     */
    public static String encode(final String str) {

        String result;

        try {
            result = URLEncoder.encode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            result = str;
        }

        return result;
    }

    /**
     * Decode a string from its XML escaped representation.
     *
     * @param   str  the string to decode
     * @return  the decoded string
     */
    public static String decode(final String str) {

        String result;

        try {
            result = URLDecoder.decode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            result = str;
        }

        return result;
    }
}
