/*
 * Copyright (c) 2009 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 *
 */

package com.jscape.util.io;

import com.jscape.util.ArrayTools;

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

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

/**
 * @author Alex Usun
 */
public class MemorySource
        implements DataSource {

    private final boolean emptyBufferReadAllowed;
    private byte[] buffer;

    public MemorySource(byte[] buffer, boolean emptyBufferReadAllowed) {
        assertNotNull(buffer);
        this.buffer = buffer;

        this.emptyBufferReadAllowed = emptyBufferReadAllowed;
    }

    public MemorySource(byte[] buffer) {
        this(buffer, true);
    }

    public MemorySource(boolean emptyBufferReadAllowed) {
        this(new byte[0], emptyBufferReadAllowed);
    }

    public MemorySource() {
        this(true);
    }

    public boolean writeAllowed() {
        return true;
    }

    public boolean readAllowed() {
        return this.buffer.length > 0 || this.emptyBufferReadAllowed;
    }

    public InputStream getInputStream()
            throws IOException {
        return new ByteArrayInputStream(this.buffer);
    }

    public OutputStream getOutputStream()
            throws IOException {
        return new java.io.ByteArrayOutputStream() {
            public void close() {
                MemorySource.this.buffer = toByteArray();
            }
        };
    }

    public byte[] buffer() {
        return this.buffer;
    }

    @Override
    public String toString() {
        return "MemorySource {"
                + "buffer=" + ArrayTools.toString(this.buffer)
                + '}';
    }
}
