/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.mq.il.uil.multiplexor;

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

import java.util.HashMap;

/**
 *  This class is used to multiplex from multiple streams into a single stream.
 *
 * @author     Hiram Chirino (Cojonudo14@hotmail.com)
 * @created    August 16, 2001
 * @version    $Revision: 1.3.4.1 $
 */
public class StreamMux {

   short            frameSize = 512;
   HashMap          openStreams = new HashMap();
   OutputStream     out;
   DataOutputStream objectOut;

   // Commands that can be sent over the admin stream.
   final static byte OPEN_STREAM_COMMAND = 0;
   final static byte CLOSE_STREAM_COMMAND = 1;
   final static byte NEXT_FRAME_SHORT_COMMAND = 2;

   /**
    *  StreamMux constructor comment.
    *
    * @param  out              java.io.OutputStream
    * @exception  IOException  Description of Exception
    */
   public StreamMux( OutputStream out )
      throws IOException {
      this.out = out;
      this.objectOut = new DataOutputStream( out );
   }

   /**
    *  Insert the method's description here. Creation date: (11/15/00 5:30:55
    *  PM)
    *
    * @param  newFrameSize     short
    * @exception  IOException  Description of Exception
    */
   public void setFrameSize( short newFrameSize )
      throws IOException {
      synchronized ( openStreams ) {
         if ( openStreams.size() > 0 ) {
            throw new IOException( "Cannot change the frame size while there are open streams." );
         }
         frameSize = newFrameSize;
      }
   }

   /**
    *  Insert the method's description here. Creation date: (11/15/00 5:30:55
    *  PM)
    *
    * @return    short
    */
   public short getFrameSize() {
      synchronized ( openStreams ) {
         return frameSize;
      }
   }

   public OutputStream getStream( short id )
      throws IOException {
      if ( id == 0 ) {
         throw new IOException( "Stream id 0 is reserved for internal use." );
      }

      OutputStream s;
      synchronized ( openStreams ) {
         s = ( OutputStream )openStreams.get( new Short( id ) );
         if ( s != null ) {
            return s;
         }

         s = new MuxOutputStream( this, id );
         openStreams.put( new Short( id ), s );
      }

      synchronized ( objectOut ) {
         objectOut.writeShort( 0 );
         // admin stream
         objectOut.writeByte( OPEN_STREAM_COMMAND );
         // command
         objectOut.writeShort( id );
         // argument
      }
      return s;
   }

   public void flush()
      throws IOException {

      synchronized ( objectOut ) {
         objectOut.flush();
         out.flush();
      }

   }

   void closeStream( short id )
      throws IOException {
      if ( id == 0 ) {
         throw new IOException( "Stream id 0 is reserved for internal use." );
      }

      synchronized ( openStreams ) {
         openStreams.remove( new Short( id ) );
      }

      synchronized ( objectOut ) {
         objectOut.writeShort( 0 );
         // admin stream
         objectOut.writeByte( CLOSE_STREAM_COMMAND );
         // command
         objectOut.writeShort( id );
         // argument
      }
   }

   void write( MuxOutputStream s, byte b[], int len )
      throws IOException {

      if ( b == null ) {
         throw new NullPointerException();
      } else if ( ( len < 0 ) || ( len > b.length ) || ( len > frameSize ) ) {
         throw new IndexOutOfBoundsException();
      } else if ( len == 0 ) {
         return;
      }

      synchronized ( objectOut ) {
         if ( len < frameSize ) {
            objectOut.writeShort( 0 );
            objectOut.writeByte( NEXT_FRAME_SHORT_COMMAND );
            objectOut.writeShort( len );
         }
         objectOut.writeShort( s.streamId );
         objectOut.write( b, 0, len );
      }
   }
}
