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;

public final class SignatureElement implements NamedElement {

    public static final String ELEMENT = "signature";
    public static final String ATTR_ALGORITHM = "algorithm";

    private final String algorithm;
    private final byte[] bytes;
    private final String base64Content;

    private SignatureElement(String algorithm, byte[] bytes, String base64Content) {
        this.algorithm = algorithm;
        this.bytes = bytes;
        this.base64Content = base64Content;
    }

    public static SignatureElement fromBytes(String algorithm, byte[] bytes) {
        return new SignatureElement(algorithm, bytes, Base64.encodeToString(bytes));
    }

    public static SignatureElement fromBase64Content(String algorithm, String base64Content) {
        return new SignatureElement(algorithm, Base64.decode(base64Content), base64Content);
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public String getBase64Content() {
        return base64Content;
    }

    public byte[] getBytes() {
        return bytes.clone();
    }

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

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