package com.wizzardo.http;

import com.wizzardo.epoll.ByteBufferProvider;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author: wizzardo
 * Date: 9/3/14
 */
public class EpollOutputStream extends OutputStream {
    private HttpConnection connection;
    private int offset;
    private byte[] buffer;
    protected volatile boolean waiting;

    public EpollOutputStream(HttpConnection connection) {
        this.connection = connection;
        buffer = new byte[1024];
        offset = 0;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        flush();
        waiting = true;
        connection.write(b, off, len, (ByteBufferProvider) Thread.currentThread());
        waitFor();
    }

    @Override
    public void close() throws IOException {
        flush();
        connection.close();
    }

    @Override
    public void flush() throws IOException {
        if (offset > 0) {
            int length = offset;
            offset = 0;
            write(buffer, 0, length);
        }
    }

    @Override
    public void write(int b) throws IOException {
        if (offset >= buffer.length)
            flush();

        buffer[offset++] = (byte) b;
    }

    protected void waitFor() {
        if (waiting) {
            synchronized (this) {
                while (waiting) {
                    try {
                        this.wait();
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }
    }

    protected void wakeUp() {
        synchronized (this) {
            waiting = false;
            this.notifyAll();
        }
    }
}

@@ -676,17 +676,19 @@
 f, len, 
-(
+get
 ByteBuff
@@ -697,16 +697,140 @@
 Provider
+());%0A        waitFor();%0A    %7D%0A%0A    protected ByteBufferProvider getByteBufferProvider() %7B%0A        return (ByteBufferProvider
 ) Thread
@@ -843,36 +843,16 @@
 ntThread
-());%0A        waitFor
 ();%0A    

add getByteBufferProvider() for inheritance