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

import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.signed.xep0285.element.DataElement;
import org.jivesoftware.smackx.signed.xep0285.element.SignatureElement;
import org.jivesoftware.smackx.signed.xep0285.element.SignedElement;

import java.io.IOException;

public class SignedElementProvider extends ExtensionElementProvider<SignedElement> {

    @Override
    public SignedElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
            throws XmlPullParserException, IOException {

        SignatureElement signature = null;
        DataElement data = null;

        XmlPullParser.TagEvent tag;
        String name;
        do {
            tag = parser.nextTag();
            name = parser.getName();
            if (tag == XmlPullParser.TagEvent.START_ELEMENT) {
                switch (name) {
                    case SignatureElement.ELEMENT:
                        String algorithm = ParserUtils.getRequiredAttribute(parser, SignatureElement.ATTR_ALGORITHM);
                        signature = SignatureElement.fromBase64Content(algorithm, parser.nextText());
                        break;

                    case DataElement.ELEMENT:
                        data = DataElement.fromBase64Content(parser.nextText());
                        break;
                }
            }
        } while (parser.getDepth() != initialDepth);

        return new SignedElement(Objects.requireNonNull(signature), Objects.requireNonNull(data));
    }
}
