using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using bareFTP.Protocol.Sftp.Streams;
using System.Threading;
using System.Runtime.CompilerServices;

namespace bareFTP.Protocol.Sftp
{
	/* -*-mode:java; c-basic-offset:2; -*- */
	/*
	Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.

	Redistribution and use In source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	  1. Redistributions of source code must retain the above copyright notice,
		 this list of conditions and the following disclaimer.

	  2. Redistributions In binary form must reproduce the above copyright 
		 notice, this list of conditions and the following disclaimer In 
		 the documentation and/or other materials provided with the distribution.

	  3. The names of the authors may not be used to endorse or promote products
		 derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
	FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
	INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
	OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
	EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	*/


	public abstract class Channel
	{
		internal static int index=0; 
		private static List<Channel> pool = new List<Channel>();
		internal static Channel getChannel(string type)
		{
			
			if(type.Equals("session"))
			{
				return new ChannelSession();
			}
			
			if(type.Equals("sftp"))
			{
				return new ChannelSftp();
			}
			
			return null;
		}
		internal static Channel getChannel(int id, Session session)
		{
			lock(pool)
			{
				foreach(Channel c in pool)
				{
					if(c.id == id && c.session == session)
						return c;
				}
			}
			return null;
		}
		internal static void del(Channel c)
		{
			lock(pool)
			{
				pool.Remove(c);
			}
		}

		internal int id;
		internal int recipient=-1;
		internal byte[] type= System.Text.Encoding.Default.GetBytes("foo");
		internal int lwsize_max=0x100000;
		internal int lwsize=0x100000;  // local initial window size
		internal int lmpsize=0x4000;     // local maximum packet size

		internal int rwsize=0;         // remote initial window size
		internal int rmpsize=0;        // remote maximum packet size

		internal IO io = null;    
		internal Thread thread=null;

		internal bool eof_local=false;
		internal bool _eof_remote=false;

		internal bool _close=false;
		internal bool connected=false;

		internal int exitstatus=-1;

		internal int reply=0; 

		internal Session session;

		internal Channel()
		{
			lock(pool)
			{
				id=index++;
				pool.Add(this);
			}
		}
		internal virtual void setRecipient(int foo)
		{
			this.recipient=foo;
		}
		internal virtual int getRecipient()
		{
			return recipient;
		}

		public virtual void init()
		{
		}

		public virtual void connect()
		{
			if(!session.isConnected())
			{
				throw new Exception("session is down");
			}
			try
			{
				Buffer buf=new Buffer(100);
				Packet packet=new Packet(buf);
				// send
				// byte   SSH_MSG_CHANNEL_OPEN(90)
				// string channel type         //
				// uint32 sender channel       // 0
				// uint32 initial window size  // 0x100000(65536)
				// uint32 maxmum packet size   // 0x4000(16384)
				packet.reset();
				buf.putByte((byte)90);
				buf.putString(this.type);
				buf.putInt(this.id);
				buf.putInt(this.lwsize);
				buf.putInt(this.lmpsize);
				session.write(packet);

				int retry=1000;
				while(this.getRecipient()==-1 &&
					session.isConnected() &&
					retry>0)
				{
					try{Thread.Sleep(50);}
					catch(Exception){}
					retry--;
				}
				if(!session.isConnected())
				{
					throw new Exception("session is down");
				}
				if(retry==0)
				{
					throw new Exception("channel is not opened.");
				}
				connected=true;
				start();
			}
			catch(Exception e)
			{
				connected=false;
				if(e is Exception) throw (Exception)e;
			}
		}

		
		public virtual void start(){}

		public bool isEOF() {return _eof_remote;}

		internal virtual void getData(Buffer buf)
		{
			setRecipient(buf.getInt());
			setRemoteWindowSize(buf.getInt());
			setRemotePacketSize(buf.getInt());
		}

		public virtual void setInputStream(Stream In)
		{
			io.setInputStream(In, false);
		}
		public virtual void setInputStream(Stream In, bool dontclose)
		{
			io.setInputStream(In, dontclose);
		}
		public virtual void setOutputStream(Stream Out)
		{
			io.setOutputStream(Out, false);
		}
		public virtual void setOutputStream(Stream Out, bool dontclose)
		{
			io.setOutputStream(Out, dontclose);
		}
		
		
		internal class MyPipedInputStream : PipedInputStream
		{
			internal MyPipedInputStream():base() { ; }
			internal MyPipedInputStream(int size) :base()
			{
				buffer=new byte[size];
			}
			internal MyPipedInputStream(PipedOutputStream Out):base(Out) { }
			internal MyPipedInputStream(PipedOutputStream Out, int size):base(Out) 
			{
				buffer=new byte[size];
			}
		}
		
		internal virtual void setLocalWindowSizeMax(int foo){ this.lwsize_max=foo; }
		internal virtual void setLocalWindowSize(int foo){ this.lwsize=foo; }
		internal virtual void setLocalPacketSize(int foo){ this.lmpsize=foo; }
		[System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.Synchronized)]
		internal virtual void setRemoteWindowSize(int foo){ this.rwsize=foo; }
		[System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.Synchronized)]
		internal virtual void addRemoteWindowSize(int foo){ this.rwsize+=foo; }
		internal virtual void setRemotePacketSize(int foo){ this.rmpsize=foo; }

		public virtual void run()
		{
		}

		internal virtual void write(byte[] foo)  
		{
			write(foo, 0, foo.Length);
		}
		internal virtual void write(byte[] foo, int s, int l)  
		{
			try
			{
				io.put(foo, s, l);
			}
			catch(NullReferenceException){}
		}
		
		
		internal virtual void eof_remote()
		{
			_eof_remote=true;
			try
			{
				if(io.outs!=null)
				{
					io.outs.Close();
					io.outs=null;
				}
			}
			catch(NullReferenceException){}
			catch(IOException){}
		}

		internal virtual void eof()
		{
			if(_close)return;
			if(eof_local)return;
			eof_local=true;
			try
			{
				Buffer buf=new Buffer(100);
				Packet packet=new Packet(buf);
				packet.reset();
				buf.putByte((byte)Session.SSH_MSG_CHANNEL_EOF);
				buf.putInt(getRecipient());
				session.write(packet);
			}
			catch(Exception)
			{
			}
			
		}

		
		internal virtual void close()
		{
			
			if(_close)return;
			_close=true;
			try
			{
				Buffer buf=new Buffer(100);
				Packet packet=new Packet(buf);
				packet.reset();
				buf.putByte((byte)Session.SSH_MSG_CHANNEL_CLOSE);
				buf.putInt(getRecipient());
				session.write(packet);
			}
			catch(Exception)
			{
			}
		}
		public virtual bool isClosed()
		{
			return _close;
		}
		internal static void disconnect(Session session)
		{
			List<Channel> channels = null;
			
			lock(pool)
			{
				channels= new List<Channel>();
				foreach(Channel c in pool)
				{
					if(c.session == session)
						channels.Add(c);
				}
			}
			foreach(Channel c in channels)
			{
				c.disconnect();
			}
		}


		public virtual void disconnect()
		{
			
			if(!connected)
			{
				return;
			}
			connected=false;

			close();

			_eof_remote=eof_local=true;

			thread=null;

			try
			{
				if(io!=null)
				{
					io.close();
				}
			}
			catch(Exception)
			{
				
			}
			io=null;
			Channel.del(this);
		}

		public virtual bool isConnected()
		{
			if(this.session!=null)
			{
				return session.isConnected() && connected;
			}
			return false;
		}

		internal virtual void setExitStatus(int foo){ exitstatus=foo; }
		public virtual int getExitStatus(){ return exitstatus; }

		internal virtual void setSession(Session session)
		{
			this.session=session;
		}
		public virtual Session getSession(){ return session; }
		public virtual int getId(){ return id; }

		public event EventHandler LogTextEmitted;
		public virtual void OnLogTextEmitted(LogTextEmittedArgs e)
		{
			LogTextEmitted(this, e);
		}
		
	}
	
}
