package sharin.doc.builder;

import java.util.List;

import sharin.util.StringUtils;

public class GenericXmlElem<E extends Elem> extends Elem {

    public GenericXmlElem(String name, Object... nodes) {
        super(name, nodes);
    }

    @SuppressWarnings("unchecked")
    @Override
    public E attr(String name, Object value) {
        return (E) super.attr(name, value);
    }

    @SuppressWarnings("unchecked")
    @Override
    public E _(Object... nodes) {
        return (E) super._(nodes);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("<");
        builder.append(StringUtils.escapeXml(getName()));

        for (Attr attr : getAttrList()) {
            builder.append(" ");
            builder.append(StringUtils.escapeXml(attr.getName()));
            builder.append("=\"");
            builder.append(StringUtils.escapeXml(String
                    .valueOf(attr.getValue())));
            builder.append('"');
        }

        List<Object> nodeList = getNodeList();

        if (nodeList.size() > 0) {
            builder.append(">");

            for (Object node : nodeList) {
                String s = node.toString();

                if (!(node instanceof Elem)) {
                    s = StringUtils.escapeXml(s);
                }

                builder.append(s);
            }

            builder.append("</");
            builder.append(StringUtils.escapeXml(getName()));
            builder.append(">");

        } else {
            builder.append(" />");
        }

        return builder.toString();
    }
}
