/*
 * Decompiled with CFR 0.152.
 */
package org.jivesoftware.smack.compression;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;

public class Java7ZlibInputOutputStream
extends XMPPInputOutputStream {
    private static final Method method;
    private static final boolean supported;
    private static final int compressionLevel = -1;
    private static final int SYNC_FLUSH_INT = 2;
    private static final int FULL_FLUSH_INT = 3;

    public Java7ZlibInputOutputStream() {
        super("zlib");
    }

    @Override
    public boolean isSupported() {
        return supported;
    }

    @Override
    public InputStream getInputStream(InputStream inputStream) {
        return new InflaterInputStream(inputStream, new Inflater(), 512){

            @Override
            public int available() throws IOException {
                if (this.inf.needsInput()) {
                    return 0;
                }
                return super.available();
            }
        };
    }

    @Override
    public OutputStream getOutputStream(OutputStream outputStream) {
        final int flushMethodInt = flushMethod == XMPPInputOutputStream.FlushMethod.SYNC_FLUSH ? 2 : 3;
        return new DeflaterOutputStream(outputStream, new Deflater(-1)){

            @Override
            public void flush() throws IOException {
                if (!supported) {
                    super.flush();
                    return;
                }
                try {
                    int count;
                    while ((count = ((Integer)method.invoke(this.def, this.buf, 0, this.buf.length, flushMethodInt)).intValue()) != 0) {
                        this.out.write(this.buf, 0, count);
                    }
                }
                catch (IllegalArgumentException e) {
                    throw new IOException("Can't flush");
                }
                catch (IllegalAccessException e) {
                    throw new IOException("Can't flush");
                }
                catch (InvocationTargetException e) {
                    throw new IOException("Can't flush");
                }
                super.flush();
            }
        };
    }

    static {
        Method m = null;
        try {
            m = Deflater.class.getMethod("deflate", byte[].class, Integer.TYPE, Integer.TYPE, Integer.TYPE);
        }
        catch (SecurityException e) {
        }
        catch (NoSuchMethodException noSuchMethodException) {
            // empty catch block
        }
        method = m;
        supported = method != null;
    }
}
