package org.jivesoftware.smackx.signed.xep0285.element;

import org.jivesoftware.smack.packet.NamedElement;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smack.util.stringencoder.Base64;

import java.nio.charset.StandardCharsets;

public final class DataElement implements NamedElement {

    public static final String ELEMENT = "data";

    private final String base64Content;
    private final String utf8Content;

    private DataElement(String utf8Content, String base64Content) {
        this.utf8Content = utf8Content;
        this.base64Content = base64Content;
    }

    public static DataElement fromUtf8Content(String utf8Content) {
        return new DataElement(utf8Content, Base64.encodeToString(utf8Content.getBytes(StandardCharsets.UTF_8)));
    }

    public static DataElement fromBase64Content(String base64Content) {
        return new DataElement(Base64.decodeToString(base64Content), base64Content);
    }

    public static DataElement fromPlainElement(PlainElement element) {
        return fromUtf8Content(element.toXML().toString());
    }

    public String getUtf8Content() {
        return utf8Content;
    }

    public byte[] getUtf8Bytes() {
        return getUtf8Content().getBytes(StandardCharsets.UTF_8);
    }

    public String getBase64Content() {
        return base64Content;
    }

    @Override
    public String getElementName() {
        return ELEMENT;
    }

    @Override
    public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) {
        return new XmlStringBuilder(this)
                .rightAngleBracket()
                .append(getBase64Content())
                .closeElement(this);
    }
}
