#!/bin/sh
# Write a small binary Android XML document with AxmlWriter, read it back
# with AxmlReader and check the element, attributes and namespace.
set -eu
cd "$AUTOPKGTEST_TMP"
J=/usr/share/java
cat > RoundTrip.java <<'EOF'
import pxb.android.axml.*;

public class RoundTrip {
    static final String A = "http://schemas.android.com/apk/res/android";
    public static void main(String[] args) throws Exception {
        AxmlWriter w = new AxmlWriter();
        w.ns("android", A, -1);
        NodeVisitor manifest = w.child(null, "manifest");
        manifest.attr(null, "package", -1, NodeVisitor.TYPE_STRING, "org.debian.test");
        manifest.attr(A, "versionCode", 0x0101021b, NodeVisitor.TYPE_FIRST_INT, 42);
        NodeVisitor app = manifest.child(null, "application");
        app.end();
        manifest.end();
        w.end();
        byte[] data = w.toByteArray();

        final StringBuilder sb = new StringBuilder();
        new AxmlReader(data).accept(new AxmlVisitor() {
            public void ns(String prefix, String uri, int ln) { sb.append("ns ").append(prefix).append('\n'); }
            public NodeVisitor child(String ns, String name) {
                sb.append("node ").append(name).append('\n');
                return new NodeVisitor() {
                    public void attr(String ns, String name, int id, int type, Object v) {
                        sb.append("attr ").append(name).append('=').append(v).append('\n');
                    }
                    public NodeVisitor child(String ns, String name) {
                        sb.append("node ").append(name).append('\n');
                        return this;
                    }
                };
            }
        });
        System.out.print(sb);
    }
}
EOF
out=$(java -cp "$J/axml.jar:$J/slf4j-api.jar" RoundTrip.java)
want='ns android
node manifest
attr package=org.debian.test
attr versionCode=42
node application'
[ "$out" = "$want" ] || { echo "FAIL: got"; echo "$out"; exit 1; }
echo "ok: written and read back"
