package com.flurry.org.apache.avro.file;

import com.flurry.android.Constants;
import com.flurry.org.apache.avro.AvroRuntimeException;
import com.flurry.org.apache.avro.Schema;
import com.flurry.org.apache.avro.file.DataFileStream;
import com.flurry.org.apache.avro.generic.GenericDatumReader;
import com.flurry.org.apache.avro.io.BinaryEncoder;
import com.flurry.org.apache.avro.io.DatumWriter;
import com.flurry.org.apache.avro.io.EncoderFactory;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.rmi.server.UID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
public class DataFileWriter<D> implements Closeable, Flushable {
    private long blockCount;
    private BinaryEncoder bufOut;
    private NonCopyingByteArrayOutputStream buffer;
    private Codec codec;
    private DatumWriter<D> dout;
    private boolean isOpen;
    private DataFileWriter<D>.BufferedFileOutputStream out;
    private Schema schema;
    private byte[] sync;
    private BinaryEncoder vout;
    private final Map<String, byte[]> meta = new HashMap();
    private int syncInterval = DataFileConstants.DEFAULT_SYNC_INTERVAL;

    public DataFileWriter(DatumWriter<D> dout) {
        this.dout = dout;
    }

    private void assertOpen() {
        if (!this.isOpen) {
            throw new AvroRuntimeException("not open");
        }
    }

    private void assertNotOpen() {
        if (this.isOpen) {
            throw new AvroRuntimeException("already open");
        }
    }

    public DataFileWriter<D> setCodec(CodecFactory c) {
        assertNotOpen();
        this.codec = c.createInstance();
        setMetaInternal(DataFileConstants.CODEC, this.codec.getName());
        return this;
    }

    public DataFileWriter<D> setSyncInterval(int syncInterval) {
        if (syncInterval < 32 || syncInterval > 1073741824) {
            throw new IllegalArgumentException("Invalid syncInterval value: " + syncInterval);
        }
        this.syncInterval = syncInterval;
        return this;
    }

    public DataFileWriter<D> create(Schema schema, File file) throws IOException {
        return create(schema, new FileOutputStream(file));
    }

    public DataFileWriter<D> create(Schema schema, OutputStream outs) throws IOException {
        assertNotOpen();
        this.schema = schema;
        setMetaInternal(DataFileConstants.SCHEMA, schema.toString());
        this.sync = generateSync();
        init(outs);
        this.vout.writeFixed(DataFileConstants.MAGIC);
        this.vout.writeMapStart();
        this.vout.setItemCount(this.meta.size());
        for (Map.Entry<String, byte[]> entry : this.meta.entrySet()) {
            this.vout.startItem();
            this.vout.writeString(entry.getKey());
            this.vout.writeBytes(entry.getValue());
        }
        this.vout.writeMapEnd();
        this.vout.writeFixed(this.sync);
        this.vout.flush();
        return this;
    }

    public DataFileWriter<D> appendTo(File file) throws IOException {
        assertNotOpen();
        if (!file.exists()) {
            throw new FileNotFoundException("Not found: " + file);
        }
        RandomAccessFile raf = new RandomAccessFile(file, Constants.ALIGN_RIGHT);
        FileDescriptor fd = raf.getFD();
        DataFileReader<D> reader = new DataFileReader<>(new SeekableFileInput(fd), new GenericDatumReader());
        this.schema = reader.getSchema();
        this.sync = reader.getHeader().sync;
        this.meta.putAll(reader.getHeader().meta);
        byte[] codecBytes = this.meta.get(DataFileConstants.CODEC);
        if (codecBytes != null) {
            String strCodec = new String(codecBytes, "UTF-8");
            this.codec = CodecFactory.fromString(strCodec).createInstance();
        } else {
            this.codec = CodecFactory.nullCodec().createInstance();
        }
        raf.close();
        init(new FileOutputStream(file, true));
        return this;
    }

    private void init(OutputStream outs) throws IOException {
        this.out = new BufferedFileOutputStream(outs);
        EncoderFactory efactory = new EncoderFactory();
        this.vout = efactory.binaryEncoder(this.out, null);
        this.dout.setSchema(this.schema);
        this.buffer = new NonCopyingByteArrayOutputStream(Math.min((int) (this.syncInterval * 1.25d), 1073741822));
        this.bufOut = efactory.binaryEncoder(this.buffer, null);
        if (this.codec == null) {
            this.codec = CodecFactory.nullCodec().createInstance();
        }
        this.isOpen = true;
    }

    private static byte[] generateSync() {
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            long time = System.currentTimeMillis();
            digester.update((new UID() + "@" + time).getBytes());
            return digester.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private DataFileWriter<D> setMetaInternal(String key, byte[] value) {
        assertNotOpen();
        this.meta.put(key, value);
        return this;
    }

    private DataFileWriter<D> setMetaInternal(String key, String value) {
        try {
            return setMetaInternal(key, value.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public DataFileWriter<D> setMeta(String key, byte[] value) {
        if (isReservedMeta(key)) {
            throw new AvroRuntimeException("Cannot set reserved meta key: " + key);
        }
        return setMetaInternal(key, value);
    }

    public static boolean isReservedMeta(String key) {
        return key.startsWith("avro.");
    }

    public DataFileWriter<D> setMeta(String key, String value) {
        try {
            return setMeta(key, value.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public DataFileWriter<D> setMeta(String key, long value) {
        return setMeta(key, Long.toString(value));
    }

    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
    public static class AppendWriteException extends RuntimeException {
        public AppendWriteException(Exception e) {
            super(e);
        }
    }

    public void append(D datum) throws IOException {
        assertOpen();
        int usedBuffer = bufferInUse();
        try {
            this.dout.write(datum, this.bufOut);
            this.blockCount++;
            writeIfBlockFull();
        } catch (IOException e) {
            resetBufferTo(usedBuffer);
            throw new AppendWriteException(e);
        } catch (RuntimeException re) {
            resetBufferTo(usedBuffer);
            throw new AppendWriteException(re);
        }
    }

    private void resetBufferTo(int size) throws IOException {
        this.bufOut.flush();
        byte[] data = this.buffer.toByteArray();
        this.buffer.reset();
        this.buffer.write(data, 0, size);
    }

    public void appendEncoded(ByteBuffer datum) throws IOException {
        assertOpen();
        int start = datum.position();
        this.bufOut.writeFixed(datum.array(), start, datum.limit() - start);
        this.blockCount++;
        writeIfBlockFull();
    }

    private int bufferInUse() {
        return this.buffer.size() + this.bufOut.bytesBuffered();
    }

    private void writeIfBlockFull() throws IOException {
        if (bufferInUse() >= this.syncInterval) {
            writeBlock();
        }
    }

    public void appendAllFrom(DataFileStream<D> otherFile, boolean recompress) throws IOException {
        assertOpen();
        Schema otherSchema = otherFile.getSchema();
        if (!this.schema.equals(otherSchema)) {
            throw new IOException("Schema from file " + otherFile + " does not match");
        }
        writeBlock();
        Codec otherCodec = otherFile.resolveCodec();
        DataFileStream.DataBlock nextBlockRaw = null;
        if (this.codec.equals(otherCodec) && !recompress) {
            while (otherFile.hasNextBlock()) {
                nextBlockRaw = otherFile.nextRawBlock(nextBlockRaw);
                nextBlockRaw.writeBlockTo(this.vout, this.sync);
            }
            return;
        }
        while (otherFile.hasNextBlock()) {
            nextBlockRaw = otherFile.nextRawBlock(nextBlockRaw);
            nextBlockRaw.decompressUsing(otherCodec);
            nextBlockRaw.compressUsing(this.codec);
            nextBlockRaw.writeBlockTo(this.vout, this.sync);
        }
    }

    private void writeBlock() throws IOException {
        if (this.blockCount > 0) {
            this.bufOut.flush();
            ByteBuffer uncompressed = this.buffer.getByteArrayAsByteBuffer();
            DataFileStream.DataBlock block = new DataFileStream.DataBlock(uncompressed, this.blockCount);
            block.compressUsing(this.codec);
            block.writeBlockTo(this.vout, this.sync);
            this.buffer.reset();
            this.blockCount = 0L;
        }
    }

    public long sync() throws IOException {
        assertOpen();
        writeBlock();
        return this.out.tell();
    }

    @Override // java.io.Flushable
    public void flush() throws IOException {
        sync();
        this.vout.flush();
    }

    @Override // java.io.Closeable, java.lang.AutoCloseable
    public void close() throws IOException {
        flush();
        this.out.close();
        this.isOpen = false;
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
    public class BufferedFileOutputStream extends BufferedOutputStream {
        private long position;

        static /* synthetic */ long access$014(BufferedFileOutputStream x0, long x1) {
            long j = x0.position + x1;
            x0.position = j;
            return j;
        }

        /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
        private class PositionFilter extends FilterOutputStream {
            public PositionFilter(OutputStream out) throws IOException {
                super(out);
            }

            @Override // java.io.FilterOutputStream, java.io.OutputStream
            public void write(byte[] b, int off, int len) throws IOException {
                this.out.write(b, off, len);
                BufferedFileOutputStream.access$014(BufferedFileOutputStream.this, len);
            }
        }

        public BufferedFileOutputStream(OutputStream out) throws IOException {
            super(null);
            this.out = new PositionFilter(out);
        }

        public long tell() {
            return this.position + this.count;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/0.dex */
    public static class NonCopyingByteArrayOutputStream extends ByteArrayOutputStream {
        NonCopyingByteArrayOutputStream(int initialSize) {
            super(initialSize);
        }

        ByteBuffer getByteArrayAsByteBuffer() {
            return ByteBuffer.wrap(this.buf, 0, this.count);
        }
    }
}
