package org.jivesoftware.smackx.ikey.element;

import org.apache.xml.security.Init;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.apache.xml.security.parser.XMLParserException;
import org.jivesoftware.smackx.ikey.util.canonicalization.XmlSecElementCanonicalizer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class XmlSecElementCanonicalizerTest {

    @BeforeAll
    public static void initialize() {
        if (!Init.isInitialized()) {
            Init.init();
        }
    }

    @Test
    public void test() throws InvalidCanonicalizerException, XMLParserException, IOException, CanonicalizationException {
        XmlSecElementCanonicalizer canonicalizer = new XmlSecElementCanonicalizer(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS));
        String element = "<ikey xmlns='urn:xmpp:ikey:0' type='OX'><subordinates jid='alice@wonderland.lit'>" +
                "<sub uri='xmpp:alice@wonderland.lit?;node=urn:xmpp:openpgp:0:public-keys:34669E842617A0D38A96016B359160D0B0868569;item=2020-01-21T10:46:21Z' fpr='34669E842617A0D38A96016B359160D0B0868569'/>" +
                "</subordinates>" +
                "<proof>iF4EABMIAAYFAl9I3esACgkQNZFg0LCGhWntNAD+LDO/Q+WQ5TrQOt4vBcqnUarCOZ6Ev4Wp4QgsIjs2BHcA/2BOIC6FBqkx80zB8NZsZu4H1fvn+gWgrscXhgf9+f+h</proof>" +
                "</ikey>";
        String elementWithInsignificantWhitespace = "" +
                "<ikey xmlns='urn:xmpp:ikey:0'\n" +
                "      type='OX'>\n" +
                "    <subordinates jid='alice@wonderland.lit'>\n" +
                "        <sub uri=\"xmpp:alice@wonderland.lit?;node=urn:xmpp:openpgp:0:public-keys:34669E842617A0D38A96016B359160D0B0868569;item=2020-01-21T10:46:21Z\"\n" +
                "             fpr='34669E842617A0D38A96016B359160D0B0868569'/>\n" +
                "    </subordinates>\n" +
                "    <proof>iF4EABMIAAYFAl9I3esACgkQNZFg0LCGhWntNAD+LDO/Q+WQ5TrQOt4vBcqnUarCOZ6Ev4Wp4QgsIjs2BHcA/2BOIC6FBqkx80zB8NZsZu4H1fvn+gWgrscXhgf9+f+h</proof>\n" +
                "</ikey>";
        String can1 = canonicalizer.removeInterElementWhitespace(new String(canonicalizer.canonicalize(element), StandardCharsets.UTF_8));
        String can2 = canonicalizer.removeInterElementWhitespace(new String(canonicalizer.canonicalize(elementWithInsignificantWhitespace), StandardCharsets.UTF_8));
        assertEquals(can1, can2);
    }
}
