package info.knacki.pass.io;

import org.bouncycastle.crypto.tls.ByteQueue;

import java.io.InputStream;
import java.io.OutputStream;

public class AppendableInputStream extends InputStream {
    private boolean fClosed;
    private final ByteQueue buffer;
    private final Writer fWriter;

    public class Writer extends OutputStream {
        @Override
        public void write(int b) {
            buffer.addData(new byte[] {(byte) (b & 0xFF)}, 0, 1);
        }

        public void close() {
            fClosed = true;
        }
    }

    public AppendableInputStream() {
        buffer = new ByteQueue(256);
        fWriter = this.new Writer();
        fClosed = false;
    }

    public Writer GetWriter() {
        return fWriter;
    }

    @Override
    public int read() {
        if (buffer.available() > 0)
            return buffer.removeData(1, 0)[0] & 0xFF;
        return -1;
    }

    @Override
    public int read(byte[] b) {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) {
        if (fClosed)
            return 0;
        int maxRead = Math.min(len, available());
        buffer.removeData(b, off, maxRead, 0);
        return maxRead;
    }

    @Override
    public int available() {
        return fClosed ? 0 : buffer.available();
    }

    @Override
    public void close() {
        fWriter.close();
    }
}
