package com.jscape.util.net.connection;

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

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public interface SyncRawConnection
        extends RawConnection {

    int read()
            throws ConnectionException;

    int read(byte[] data, int offset, int length)
            throws ConnectionException;

    int availableBytes()
            throws ConnectionException;

    class ConnectionInputStream
            extends InputStream {

        private final SyncRawConnection base;

        public ConnectionInputStream(SyncRawConnection base) {
            assertNotNull(base);
            this.base = base;
        }

        @Override
        public int available()
                throws IOException {
            return this.base.availableBytes();
        }

        @Override
        public int read()
                throws IOException {
            return this.base.read();
        }

        @Override
        public int read(byte[] buffer, int offset, int length)
                throws IOException {
            return this.base.read(buffer, offset, length);
        }

    }

    class ConnectionOutputStream
            extends OutputStream {

        private final SyncRawConnection base;

        public ConnectionOutputStream(SyncRawConnection base) {
            assertNotNull(base);
            this.base = base;
        }

        @Override
        public void write(int data)
                throws IOException {
            this.base.write((byte) data);
        }

        @Override
        public void write(byte[] buffer, int offset, int length)
                throws IOException {
            this.base.write(buffer, offset, length);
        }

        @Override
        public void flush()
                throws IOException {
            this.base.flush();
        }
    }
}
