/* PipedInputStream.cs
   Converted from java for bareFTP by Christian Eide
   Original Copyright follows
 */

/* PipedInputStream.java -- Read portion of piped streams.
   Copyright (C) 1998, 1999, 2000, 2001, 2003, 2005  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
 
GNU Classpath 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
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */



using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;



namespace bareFTP.Protocol.Sftp.Streams
{

	public class PipedInputStream : Stream
	{
		
		public PipedOutputStream source;
		internal bool closed;
		internal const int PIPE_SIZE = 1024;
		internal byte[] buffer = new byte[PIPE_SIZE];
		internal int m_in = -1;
		internal int m_out = 0;
		internal byte[] read_buf = new byte[1];
		
		public PipedInputStream() 
		{
		}

		public PipedInputStream(PipedOutputStream source) 
		{
			connect(source);
		}

		
		public virtual void connect(PipedOutputStream source)
		{
			if(this.source != null || source.sink != null)
				throw new Exception("Already connected");
			
			source.sink = this;
			this.source = source;
		}

		/**
		 * Receives a byte of data.  This method will block if no input is
		 * available.
		 * @param b the byte being received
		 * @exception IOException If the pipe is broken.
		 * @since     JDK1.1
		 */
		[MethodImpl(MethodImplOptions.Synchronized)]
		internal void receive(int val) 
		{
			read_buf[0] = (byte)(val & 0xFF);
			receive(read_buf, 0 ,1);
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		internal void receive(byte[] buf, int offset, int len) 
		{
			if(closed)
				throw new IOException("Pipe closed");
			
			int bufpos = offset;
			int copylen;
			
			while (len > 0) 
			{
				try
				{
					while (m_in == m_out)
					{
						Monitor.PulseAll(this);
						Monitor.Wait(this, 1000);
						
						if(closed)
							throw new IOException("Pipe closed");
					}
				}
				catch (ThreadInterruptedException ex) 
				{
					throw ex;
				}
			
				if(m_in < 0) // the pipe is empty
					m_in = 0;
				if(m_in < m_out)
					copylen = Math.Min(len, m_out - m_in);
				else
					copylen = Math.Min(len, buffer.Length - m_in);
				
				bareFTP.Protocol.Sftp.Util.arraycopy(buf, bufpos, buffer, m_in, copylen);
				
				len -= copylen;
				bufpos += copylen;
				m_in += copylen;
				if (m_in == buffer.Length)
					m_in = 0;
			
			}
			
			Monitor.PulseAll(this);
		}
		
		public override int ReadByte()
		{
			int r = Read(read_buf, 0, 1);
			return r != -1 ? (read_buf[0] & 0xFF) : -1;
			
		}
		
		[MethodImpl(MethodImplOptions.Synchronized)]
		public override int Read(byte[] buf, int offset, int len)
		{
			if (source == null)
				throw new IOException ("Not connected");
			if (closed)
				throw new IOException ("Pipe closed");

			// If the buffer is empty, wait until there is something in the pipe 
			// to read.
			try
			{
				while (m_in < 0)
				{
					if (source.closed)
						return -1;
					Monitor.Wait(this, 1000);
				}
			}
			catch (ThreadInterruptedException)
			{
				throw new ThreadInterruptedException();
			}
    
			int total = 0;
			int copylen;
    
			while (true)
			{
				// Figure out how many bytes from the pipe can be copied without 
				// overrunning in or going past the length of buf.
				if (m_out < m_in)
					copylen = Math.Min (len, m_in - m_out);
				else
					copylen = Math.Min (len, buffer.Length - m_out);

				bareFTP.Protocol.Sftp.Util.arraycopy(buffer, m_out, buf, offset, copylen);
				offset += copylen;
				len -= copylen;
				m_out += copylen;
				total += copylen;
	
				if (m_out == buffer.Length)
					m_out = 0;
	
				if (m_out == m_in)
				{
					// Pipe is now empty.
					m_in = -1;
					m_out = 0;
				}

				// If output buffer is filled or the pipe is empty, we're done.
				if (len == 0 || m_in == -1)
				{
					// Notify any waiting outputstream that there is now space
					// to write.
					Monitor.PulseAll(this);
					return total;
				}
			}
		}
		
		[MethodImpl(MethodImplOptions.Synchronized)]
		public int available()
		{
			if (m_in < 0)
				return 0;
			else if (m_out < m_in)
				return m_in - m_out;
			else
				return (buffer.Length - m_out) + m_in;
		}
		
		
		
		////////////////
		
		public override void WriteByte(byte value)
		{
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
		}
		
		public override void Close()
		{
			base.Close ();
			closed = true;
			Monitor.PulseAll(this);			
		}
		public override bool CanRead
		{
			get
			{
				return true;
			}
		}
		public override bool CanWrite
		{
			get
			{
				return false;
			}
		}
		public override bool CanSeek
		{
			get
			{
				return false;
			}
		}
		public override void Flush()
		{
			
		}
		public override long Length
		{
			get
			{
				if(m_in > m_out)
					return (m_in - m_out);
				else
				{
					return (buffer.Length -m_out+m_in);
				}
			}
		}
		public override long Position
		{
			get
			{
				return m_out;
			}
			set
			{
				throw new IOException("Setting the position of this stream is not supported");
			}
		}
		public override void SetLength(long value)
		{
			throw new IOException("Setting the length of this stream is not supported");
		}
		public override long Seek(long offset, SeekOrigin origin)
		{
			return 0;
		}
		
		/// </summary>
		
	}
}
