package org.maachang.jni.io;

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

/**
 * Snappy圧縮処理.
 * 
 * @version 2012/11/09
 * @author  masahito suzuki
 * @since   SeabassNativeIO-1.0.3
 */
public class SnappyOutputStream extends OutputStream {
    protected static final byte[] MAGIC = new byte[]{(byte)'@',(byte)'G',(byte)'S',(byte)'N',(byte)'P'} ;
    protected static final int MAGIC_LENGTH = MAGIC.length ;
    
    protected static final int WRITE_BUFFER_LENGTH = 0x00100000 ;
    protected static final int DEST_BUFFER_LENGTH = Snappy.calcMaxCompressLength( WRITE_BUFFER_LENGTH ) + 4 ;
    
    private OutputStream parent = null ;
    private boolean _first = true ;
    private long _srcAddr = 0L ;
    private int _srcPos = 0 ;
    private long _destAddr = 0L ;
    private byte[] _tmp = null ;
    private final int[] _destLen = new int[ 1 ] ;
    
    private SnappyOutputStream() {
        
    }
    
    /**
     * コンストラクタ.
     * @param parent 親OutputStreamを設定します.
     */
    public SnappyOutputStream( OutputStream parent ) {
        if( parent == null ) {
            throw new IllegalArgumentException( "引数は不正です" ) ;
        }
        this.parent = parent ;
        _srcAddr = DirectMemoryIO.malloc( WRITE_BUFFER_LENGTH ) ;
        _destAddr = DirectMemoryIO.malloc( DEST_BUFFER_LENGTH ) ;
        _tmp = new byte[ DEST_BUFFER_LENGTH ] ;
    }
    
    /** デストラクタ. **/
    protected void finalize() throws Exception {
        try {
            close() ;
        } catch( Exception e ) {
        }
    }
    
    /**
     * クローズ処理.
     * @exception Exception 例外.
     */
    public void close() throws IOException {
        if( _srcAddr == 0L ) {
            return ;
        }
        flush() ;
        DirectMemoryIO.free( _srcAddr ) ;
        _srcAddr = 0L ;
        DirectMemoryIO.free( _destAddr ) ;
        _destAddr = 0L ;
        _tmp = null ;
        _first = true ;
        
        parent.close() ;
    }
    
    /**
     * 更新.
     * @exception IOException I/O例外.
     */
    public void flush() throws IOException {
        if( _srcAddr == 0L ) {
            throw new IOException( "既にクローズしています" ) ;
        }
        if( _srcPos <= 0 ) {
            return ;
        }
        NativeIO.snappyCompress( _srcAddr,_srcPos,_destAddr+4L,_destLen ) ;
        int destLen = _destLen[0] ;
        DirectMemoryIO.putInt( _destAddr,0,destLen ) ;
        DirectMemoryIO.getBinary( _destAddr,0,_tmp,0,destLen+4 ) ;
        if( _first ) {
            parent.write( MAGIC,0,MAGIC_LENGTH ) ;
            _first = false ;
        }
        parent.write( _tmp,0,destLen+4 ) ;
        parent.flush() ;
        _srcPos = 0 ;
    }
    
    /**
     * 書き込み処理.
     * @param b 書き込み情報を設定します.
     * @exception IOException I/O例外.
     */
    public void write(int b) throws IOException {
        if( _srcAddr == 0L ) {
            throw new IOException( "既にクローズしています" ) ;
        }
        if( _srcPos >= WRITE_BUFFER_LENGTH ) {
            flush() ;
        }
        DirectMemoryIO.put( _srcAddr,_srcPos,(byte)b ) ;
        _srcPos ++ ;
    }
    
    /**
     * 書き込み処理.
     * @param b 対象のバイナリを設定します.
     * @exception IOException I/O例外.
     */
    public void write(byte[] b) throws IOException {
        if (b == null) {
            throw new NullPointerException( "バイナリが存在しません" );
        }
        write( b,0,b.length ) ;
    }
    
    /**
     * 書き込み処理.
     * @param b 対象のバイナリを設定します.
     * @exception IOException I/O例外.
     */
    public void write(byte b[], int off, int len) throws IOException {
        if( _srcAddr == 0L ) {
            throw new IOException( "既にクローズしています" ) ;
        }
        if (b == null) {
            throw new NullPointerException( "バイナリが存在しません" );
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
               ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException( "指定範囲が不正です" );
        } else if (len == 0) {
            return;
        }
        if( len > ( WRITE_BUFFER_LENGTH - _srcPos ) ) {
            int plen = ( WRITE_BUFFER_LENGTH - _srcPos ) ;
            while( true ) {
                DirectMemoryIO.putBinary( _srcAddr,_srcPos,b,off,plen ) ;
                _srcPos += plen ;
                if( _srcPos == WRITE_BUFFER_LENGTH ) {
                    flush() ;
                }
                else {
                    _srcPos = plen ;
                    break ;
                }
                off += plen ;
                len -= plen ;
                if( len < WRITE_BUFFER_LENGTH ) {
                    plen = len ;
                }
                else {
                    plen = WRITE_BUFFER_LENGTH ;
                }
            }
        }
        else {
            DirectMemoryIO.putBinary( _srcAddr,_srcPos,b,off,len ) ;
            _srcPos += len ;
        }
    }
    
    /**
     * クローズされているかチェック.
     * @return boolean [true]の場合、クローズしています.
     */
    public boolean isClose() {
        return _srcAddr == 0L ;
    }
}
