package org.jivesoftware.smackx.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.util.stringencoder.Base64;
import org.jivesoftware.smack.xml.SmackXmlParser;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.security.Security;

public class MercurySmackTestSuite {
    static {
        SmackConfiguration.getVersion();
        org.jivesoftware.smack.util.stringencoder.Base64.setEncoder(new Base64.Encoder() {

            @Override
            public byte[] decode(String string) {
                return java.util.Base64.getDecoder().decode(string);
            }

            @Override
            public String encodeToString(byte[] input) {
                return java.util.Base64.getEncoder().encodeToString(input);
            }

            @Override
            public String encodeToStringWithoutPadding(byte[] input) {
                return java.util.Base64.getEncoder().withoutPadding().encodeToString(input);
            }

            @Override
            public byte[] encode(byte[] input) {
                return java.util.Base64.getEncoder().encode(input);
            }

        });

        Security.addProvider(new BouncyCastleProvider());
    }

    public static XmlPullParser getParser(String string) {
        return getParser(string, null);
    }

    public static XmlPullParser getParser(String string, String startTag) {
        return getParser(new StringReader(string), startTag);
    }

    private static XmlPullParser getParser(Reader reader, String startTag) {
        XmlPullParser parser;
        try {
            parser = SmackXmlParser.newXmlParser(reader);
            if (startTag == null) {
                while (parser.getEventType() != XmlPullParser.Event.START_ELEMENT) {
                    parser.next();
                }
                return parser;
            }
            boolean found = false;

            while (!found) {
                if ((parser.next() == XmlPullParser.Event.START_ELEMENT) && parser.getName().equals(startTag))
                    found = true;
            }

            if (!found)
                throw new IllegalArgumentException("Can not find start tag '" + startTag + "'");
        } catch (XmlPullParserException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return parser;
    }
}
