package org.jivesoftware.smackx.ikey.provider;

import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.parsing.SmackParsingException;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.util.ParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;
import org.jivesoftware.smackx.ikey.element.SubordinateElement;
import org.jivesoftware.smackx.ikey.element.SubordinateListElement;
import org.jxmpp.jid.EntityBareJid;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SubordinateListElementProvider extends ExtensionElementProvider<SubordinateListElement> {

    public static final SubordinateListElementProvider INSTANCE = new SubordinateListElementProvider();

    @Override
    public SubordinateListElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment)
            throws XmlPullParserException, IOException, SmackParsingException {
        Date timestamp = ParserUtils.getDateFromXep82String(ParserUtils.getRequiredAttribute(parser, SubordinateListElement.ATTR_STAMP));
        EntityBareJid jid = ParserUtils.getBareJidAttribute(parser);
        List<SubordinateElement> subordinates = new ArrayList<>();
        do {
            switch (parser.nextTag()) {
                case START_ELEMENT:
                    if (SubordinateElement.ELEMENT.equals(parser.getName())) {
                        String type = ParserUtils.getRequiredAttribute(parser, SubordinateElement.ATTR_TYPE);
                        String uriString = ParserUtils.getRequiredAttribute(parser, SubordinateElement.ATTR_SUB_URI);
                        URI uri = URI.create(uriString);
                        String fingerprint = ParserUtils.getRequiredAttribute(parser, SubordinateElement.ATTR_SUB_FINGERPRINT);
                        subordinates.add(new SubordinateElement(type, uri, fingerprint));
                    }
                    break;
                case END_ELEMENT:
                    break;
            }
        } while (parser.getDepth() != initialDepth);
        return new SubordinateListElement(jid, timestamp, subordinates);
    }
}
