using System;
using System.Threading;
using System.Net.Sockets;

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 class Util
	{

		/// <summary>
		/// Converts a time_t to DateTime
		/// </summary>
		public static DateTime Time_T2DateTime(uint time_t) 
		{
			long win32FileTime = 10000000*(long)time_t + 116444736000000000;
			return DateTime.FromFileTimeUtc(win32FileTime).ToLocalTime();
		}

		internal static byte[] fromBase64(byte[] buf, int start, int length)
		{
			string s = System.Text.Encoding.Default.GetString(buf, start, length);
			return Convert.FromBase64String(s);
		}
		
		internal static byte[] toBase64(byte[] buf, int start, int length)
		{
			return System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(buf, start, length));
		}
		
		internal static bool glob(byte[] pattern, byte[] name)
		{
			return glob(pattern, 0, name, 0);
		}
		
		private static bool glob(byte[] pattern, int pattern_index,
			byte[] name, int name_index)
		{
			int patternlen=pattern.Length;
			if(patternlen==0)
				return false;
			int namelen=name.Length;
			int i=pattern_index;
			int j=name_index;
			while(i<patternlen && j<namelen)
			{
				if(pattern[i]=='\\')
				{
					if(i+1==patternlen)
						return false;
					i++;
					if(pattern[i]!=name[j]) return false;
					i++; j++;
					continue;
				}
				if(pattern[i]=='*')
				{
					if(patternlen==i+1) return true;
					i++;
					byte foo=pattern[i];
					while(j<namelen)
					{
						if(foo==name[j])
						{
							if(glob(pattern, i, name, j))
							{
								return true;
							}
						}
						j++;
					}
					return false;

				}
				if(pattern[i]=='?')
				{
					i++; j++;
					continue;
				}
				if(pattern[i]!=name[j]) return false;
				i++; j++;
				continue;
			}
			if(i==patternlen && j==namelen) return true;
			return false;
		}

		internal static bool array_equals(byte[] foo, byte[] bar)
		{
			int i=foo.Length;
			if(i!=bar.Length) return false;
			for(int j=0; j<i; j++){ if(foo[j]!=bar[j]) return false; }
			return true;
		}

		public static string getString(byte[] arr, int offset, int len)
		{
			return System.Text.Encoding.Default.GetString(arr, offset, len);
		}
			
		public static string getStringUTF8(byte[] arr, int offset, int len)
		{
			return System.Text.Encoding.UTF8.GetString(arr, offset, len);
		}

		public static string getString(byte[] arr)
		{
			return getString(arr, 0, arr.Length);
		}
			
		public static string getStringUTF8(byte[] arr)
		{
			return getStringUTF8(arr, 0, arr.Length);
		}

		public static byte[] getBytes(String str)
		{
			return System.Text.Encoding.Default.GetBytes( str );
		}
			
		public static byte[] getBytesUTF8(String str)
		{
			return System.Text.Encoding.UTF8.GetBytes( str );
		}

		public static bool regionMatches(String orig, bool ignoreCase, int toffset,
			String other, int ooffset, int len) 
		{
			char[] ta = new char[orig.Length];
			char[] pa = new char[other.Length];
			orig.CopyTo(0, ta, 0, orig.Length);
			int to = toffset;
			other.CopyTo(0, pa, 0, other.Length);
			int po = ooffset;
			// Note: toffset, ooffset, or len might be near -1>>>1.
			if ((ooffset < 0) || (toffset < 0) || (toffset > (long)orig.Length - len) ||
				(ooffset > (long)other.Length - len)) 
			{
				return false;
			}
			while (len-- > 0) 
			{
				char c1 = ta[to++];
				char c2 = pa[po++];
				if (c1 == c2) 
				{
					continue;
				}
				if (ignoreCase) 
				{
					// If characters don't match but case may be ignored,
					// try converting both characters to uppercase.
					// If the results match, then the comparison scan should
					// continue.
					char u1 = char.ToUpper(c1);
					char u2 = char.ToUpper(c2);
					if (u1 == u2) 
					{
						continue;
					}
					// Unfortunately, conversion to uppercase does not work properly
					// for the Georgian alphabet, which has strange rules about case
					// conversion.  So we need to make one last check before
					// exiting.
					if (char.ToLower(u1) == char.ToLower(u2)) 
					{
						continue;
					}
				}
				return false;
			}
			return true;
		}

		public static uint ToUInt32( byte [] ptr ,int Index)
		{
			uint ui = 0;

			ui = ( (uint) ptr[ Index++ ] ) << 24; 
			ui += ( (uint) ptr[ Index++ ] ) << 16;
			ui += ( (uint) ptr[ Index++ ] ) << 8;
			ui += (uint) ptr[ Index++ ];

			return ui;
		}

		public static int ToInt32( byte [] ptr ,int Index)
		{
			return (int)ToUInt32( ptr, Index );
		}

		public static ushort ToUInt16( byte [] ptr , int Index)
		{
			ushort u = 0;

			u = ( ushort ) ptr[ Index++ ];
			u *= 256;
			u += ( ushort ) ptr[ Index++ ];

			return u;
		}
		public static bool ArrayContains( Object[] arr, Object o)
		{
			for(int i=0; i<arr.Length; i++)
			{
				if (arr[i].Equals(o))
					return true;
			}
			return false;
		}
		public static bool ArrayContains( char[] arr, char c)
		{
			for(int i=0; i<arr.Length; i++)
			{
				if (arr[i] == c)
					return true;
			}
			return false;
		}
		public static bool ArrayContains( char[] arr, char c, int count)
		{
			for(int i=0; i<count; i++)
			{
				if (arr[i] == c)
					return true;
			}
			return false;
		}

		/**
		* Utility method to delete the leading zeros from the modulus.
		* @param a modulus
		* @return modulus
		*/
		public static byte[] stripLeadingZeros(byte[] a) 
		{
			int lastZero = -1;
			for (int i = 0; i < a.Length; i++) 
			{
				if (a[i] == 0) 
				{
					lastZero = i;
				}
				else 
				{
					break;
				}
			}
			lastZero++;
			byte[] result = new byte[a.Length - lastZero];
			Array.Copy(a, lastZero, result, 0, result.Length);
			return result;
		}

			
		public static string hex(byte[] arr)
		{
			string hex = "0x";
			for(int i=0;i<arr.Length; i++)
			{
				string mbyte = arr[i].ToString("X");
				if (mbyte.Length == 1)
					mbyte = "0"+mbyte;
				hex += mbyte;
			}
			return hex;
		}

		internal static string unquote(string _path)
		{
			byte[] path = System.Text.Encoding.UTF8.GetBytes(_path);
			int pathlen=path.Length;
			int i=0;
			while(i<pathlen)
			{
				if(path[i]=='\\')
				{
					if(i+1==pathlen)
					break;
					Array.Copy(path, i+1, path, i, path.Length-(i+1));
					pathlen--;
					continue;
				}
				i++;
			}
			if(pathlen==path.Length)return _path;
			byte[] foo=new byte[pathlen];
			Array.Copy(path, 0, foo, 0, pathlen);
			return System.Text.Encoding.UTF8.GetString(foo);
		}
		
		internal static bool equals(byte[] foo, byte[] bar)
		{
			int i=foo.Length;
			if(i!=bar.Length) return false;
			for(int j=0; j<i; j++){ if(foo[j]!=bar[j]) return false; }
			return true;
		}
		
		
		
		public static long skip(System.IO.Stream s, long len)
		{
			
			int i=0;
			int count = 0;
			byte[] buf = new byte[len];
			while(len>0)
			{
				i=s.Read(buf, count, (int)len);//tamir: possible lost of pressision
				if(i<=0)
				{
					throw new Exception("Stream is closed");
					//return (s-foo)==0 ? i : s-foo;
				}
				count+=i;
				len-=i;
			}
			return count;
			
		}
		
	}
}
	


