using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
	// TODO: Sort out wether tagged data is useful and what a good implementation might look like.
	// Its just a sketch of an idea at the moment.
	/// 
	/// ExtraData tagged value interface.
	/// 
	public interface ITaggedData
	{
		/// 
		/// Get the ID for this tagged data value.
		/// 
		short TagID { get; }
		/// 
		/// Set the contents of this instance from the data passed.
		/// 
		/// The data to extract contents from.
		/// The offset to begin extracting data from.
		/// The number of bytes to extract.
		void SetData(byte[] data, int offset, int count);
		/// 
		/// Get the data representing this instance.
		/// 
		/// Returns the data for this instance.
		byte[] GetData();
	}
	/// 
	/// A raw binary tagged value
	/// 
	public class RawTaggedData : ITaggedData
	{
		/// 
		/// Initialise a new instance.
		/// 
		/// The tag ID.
		public RawTaggedData(short tag)
		{
			_tag = tag;
		}
		#region ITaggedData Members
		/// 
		/// Get the ID for this tagged data value.
		/// 
		public short TagID {
			get { return _tag; }
			set { _tag = value; }
		}
		/// 
		/// Set the data from the raw values provided.
		/// 
		/// The raw data to extract values from.
		/// The index to start extracting values from.
		/// The number of bytes available.
		public void SetData(byte[] data, int offset, int count)
		{
			if (data == null) {
				throw new ArgumentNullException("nameof(data)");
			}
			_data = new byte[count];
			Array.Copy(data, offset, _data, 0, count);
		}
		/// 
		/// Get the binary data representing this instance.
		/// 
		/// The raw binary data representing this instance.
		public byte[] GetData()
		{
			return _data;
		}
		#endregion
		/// 
		/// Get /set the binary data representing this instance.
		/// 
		/// The raw binary data representing this instance.
		public byte[] Data {
			get { return _data; }
			set { _data = value; }
		}
		#region Instance Fields
		/// 
		/// The tag ID for this instance.
		/// 
		short _tag;
		byte[] _data;
		#endregion
	}
	/// 
	/// Class representing extended unix date time values.
	/// 
	public class ExtendedUnixData : ITaggedData
	{
		/// 
		/// Flags indicate which values are included in this instance.
		/// 
		[Flags]
		public enum Flags : byte
		{
			/// 
			/// The modification time is included
			/// 
			ModificationTime = 0x01,
			/// 
			/// The access time is included
			/// 
			AccessTime = 0x02,
			/// 
			/// The create time is included.
			/// 
			CreateTime = 0x04,
		}
		#region ITaggedData Members
		/// 
		/// Get the ID
		/// 
		public short TagID {
			get { return 0x5455; }
		}
		/// 
		/// Set the data from the raw values provided.
		/// 
		/// The raw data to extract values from.
		/// The index to start extracting values from.
		/// The number of bytes available.
		public void SetData(byte[] data, int index, int count)
		{
			using (MemoryStream ms = new MemoryStream(data, index, count, false))
			using (ZipHelperStream helperStream = new ZipHelperStream(ms)) {
				// bit 0           if set, modification time is present
				// bit 1           if set, access time is present
				// bit 2           if set, creation time is present
				_flags = (Flags)helperStream.ReadByte();
				if (((_flags & Flags.ModificationTime) != 0))
				{
					int iTime = helperStream.ReadLEInt();
					_modificationTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) +
						new TimeSpan(0, 0, 0, iTime, 0);
					// Central-header version is truncated after modification time
					if (count <= 5) return;
				}
				if ((_flags & Flags.AccessTime) != 0) {
					int iTime = helperStream.ReadLEInt();
					_lastAccessTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) +
						new TimeSpan(0, 0, 0, iTime, 0);
				}
				if ((_flags & Flags.CreateTime) != 0) {
					int iTime = helperStream.ReadLEInt();
					_createTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) +
						new TimeSpan(0, 0, 0, iTime, 0);
				}
			}
		}
		/// 
		/// Get the binary data representing this instance.
		/// 
		/// The raw binary data representing this instance.
		public byte[] GetData()
		{
			using (MemoryStream ms = new MemoryStream())
			using (ZipHelperStream helperStream = new ZipHelperStream(ms)) {
				helperStream.IsStreamOwner = false;
				helperStream.WriteByte((byte)_flags);     // Flags
				if ((_flags & Flags.ModificationTime) != 0) {
					TimeSpan span = _modificationTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
					var seconds = (int)span.TotalSeconds;
					helperStream.WriteLEInt(seconds);
				}
				if ((_flags & Flags.AccessTime) != 0) {
					TimeSpan span = _lastAccessTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
					var seconds = (int)span.TotalSeconds;
					helperStream.WriteLEInt(seconds);
				}
				if ((_flags & Flags.CreateTime) != 0) {
					TimeSpan span = _createTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
					var seconds = (int)span.TotalSeconds;
					helperStream.WriteLEInt(seconds);
				}
				return ms.ToArray();
			}
		}
		#endregion
		/// 
		/// Test a  value to see if is valid and can be represented here.
		/// 
		/// The value to test.
		/// Returns true if the value is valid and can be represented; false if not.
		/// The standard Unix time is a signed integer data type, directly encoding the Unix time number,
		/// which is the number of seconds since 1970-01-01.
		/// Being 32 bits means the values here cover a range of about 136 years.
		/// The minimum representable time is 1901-12-13 20:45:52,
		/// and the maximum representable time is 2038-01-19 03:14:07.
		/// 
		public static bool IsValidValue(DateTime value)
		{
			return ((value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
					(value <= new DateTime(2038, 1, 19, 03, 14, 07)));
		}
		/// 
		/// Get /set the Modification Time
		/// 
		/// 
		/// 
		public DateTime ModificationTime {
			get { return _modificationTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_flags |= Flags.ModificationTime;
				_modificationTime = value;
			}
		}
		/// 
		/// Get / set the Access Time
		/// 
		/// 
		/// 
		public DateTime AccessTime {
			get { return _lastAccessTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_flags |= Flags.AccessTime;
				_lastAccessTime = value;
			}
		}
		/// 
		/// Get / Set the Create Time
		/// 
		/// 
		/// 
		public DateTime CreateTime {
			get { return _createTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_flags |= Flags.CreateTime;
				_createTime = value;
			}
		}
		/// 
		/// Get/set the values to include.
		/// 
		public Flags Include
		{
			get { return _flags; }
			set { _flags = value; }
		}
		#region Instance Fields
		Flags _flags;
		DateTime _modificationTime = new DateTime(1970, 1, 1);
		DateTime _lastAccessTime = new DateTime(1970, 1, 1);
		DateTime _createTime = new DateTime(1970, 1, 1);
		#endregion
	}
	/// 
	/// Class handling NT date time values.
	/// 
	public class NTTaggedData : ITaggedData
	{
		/// 
		/// Get the ID for this tagged data value.
		/// 
		public short TagID {
			get { return 10; }
		}
		/// 
		/// Set the data from the raw values provided.
		/// 
		/// The raw data to extract values from.
		/// The index to start extracting values from.
		/// The number of bytes available.
		public void SetData(byte[] data, int index, int count)
		{
			using (MemoryStream ms = new MemoryStream(data, index, count, false))
			using (ZipHelperStream helperStream = new ZipHelperStream(ms)) {
				helperStream.ReadLEInt(); // Reserved
				while (helperStream.Position < helperStream.Length) {
					int ntfsTag = helperStream.ReadLEShort();
					int ntfsLength = helperStream.ReadLEShort();
					if (ntfsTag == 1) {
						if (ntfsLength >= 24) {
							long lastModificationTicks = helperStream.ReadLELong();
							_lastModificationTime = DateTime.FromFileTimeUtc(lastModificationTicks);
							long lastAccessTicks = helperStream.ReadLELong();
							_lastAccessTime = DateTime.FromFileTimeUtc(lastAccessTicks);
							long createTimeTicks = helperStream.ReadLELong();
							_createTime = DateTime.FromFileTimeUtc(createTimeTicks);
						}
						break;
					} else {
						// An unknown NTFS tag so simply skip it.
						helperStream.Seek(ntfsLength, SeekOrigin.Current);
					}
				}
			}
		}
		/// 
		/// Get the binary data representing this instance.
		/// 
		/// The raw binary data representing this instance.
		public byte[] GetData()
		{
			using (MemoryStream ms = new MemoryStream())
			using (ZipHelperStream helperStream = new ZipHelperStream(ms)) {
				helperStream.IsStreamOwner = false;
				helperStream.WriteLEInt(0);       // Reserved
				helperStream.WriteLEShort(1);     // Tag
				helperStream.WriteLEShort(24);    // Length = 3 x 8.
				helperStream.WriteLELong(_lastModificationTime.ToFileTimeUtc());
				helperStream.WriteLELong(_lastAccessTime.ToFileTimeUtc());
				helperStream.WriteLELong(_createTime.ToFileTimeUtc());
				return ms.ToArray();
			}
		}
		/// 
		/// Test a  valuie to see if is valid and can be represented here.
		/// 
		/// The value to test.
		/// Returns true if the value is valid and can be represented; false if not.
		/// 
		/// NTFS filetimes are 64-bit unsigned integers, stored in Intel
		/// (least significant byte first) byte order. They determine the
		/// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
		/// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
		/// 
		public static bool IsValidValue(DateTime value)
		{
			bool result = true;
			try {
				value.ToFileTimeUtc();
			} catch {
				result = false;
			}
			return result;
		}
		/// 
		/// Get/set the last modification time.
		/// 
		public DateTime LastModificationTime {
			get { return _lastModificationTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_lastModificationTime = value;
			}
		}
		/// 
		/// Get /set the create time
		/// 
		public DateTime CreateTime {
			get { return _createTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_createTime = value;
			}
		}
		/// 
		/// Get /set the last access time.
		/// 
		public DateTime LastAccessTime {
			get { return _lastAccessTime; }
			set {
				if (!IsValidValue(value)) {
					throw new ArgumentOutOfRangeException("nameof(value)");
				}
				_lastAccessTime = value;
			}
		}
		#region Instance Fields
		DateTime _lastAccessTime = DateTime.FromFileTimeUtc(0);
		DateTime _lastModificationTime = DateTime.FromFileTimeUtc(0);
		DateTime _createTime = DateTime.FromFileTimeUtc(0);
		#endregion
	}
	/// 
	/// A factory that creates tagged data instances.
	/// 
	interface ITaggedDataFactory
	{
		/// 
		/// Get data for a specific tag value.
		/// 
		/// The tag ID to find.
		/// The data to search.
		/// The offset to begin extracting data from.
		/// The number of bytes to extract.
		/// The located value found, or null if not found.
		ITaggedData Create(short tag, byte[] data, int offset, int count);
	}
	///
	/// 
	/// A class to handle the extra data field for Zip entries
	/// 
	/// 
	/// Extra data contains 0 or more values each prefixed by a header tag and length.
	/// They contain zero or more bytes of actual data.
	/// The data is held internally using a copy on write strategy.  This is more efficient but
	/// means that for extra data created by passing in data can have the values modified by the caller
	/// in some circumstances.
	/// 
	sealed public class ZipExtraData : IDisposable
	{
		#region Constructors
		/// 
		/// Initialise a default instance.
		/// 
		public ZipExtraData()
		{
			Clear();
		}
		/// 
		/// Initialise with known extra data.
		/// 
		/// The extra data.
		public ZipExtraData(byte[] data)
		{
			if (data == null) {
				_data = new byte[0];
			} else {
				_data = data;
			}
		}
		#endregion
		/// 
		/// Get the raw extra data value
		/// 
		/// Returns the raw byte[] extra data this instance represents.
		public byte[] GetEntryData()
		{
			if (Length > ushort.MaxValue) {
				throw new ZipException("Data exceeds maximum length");
			}
			return (byte[])_data.Clone();
		}
		/// 
		/// Clear the stored data.
		/// 
		public void Clear()
		{
			if ((_data == null) || (_data.Length != 0)) {
				_data = new byte[0];
			}
		}
		/// 
		/// Gets the current extra data length.
		/// 
		public int Length {
			get { return _data.Length; }
		}
		/// 
		/// Get a read-only  for the associated tag.
		/// 
		/// The tag to locate data for.
		/// Returns a  containing tag data or null if no tag was found.
		public Stream GetStreamForTag(int tag)
		{
			Stream result = null;
			if (Find(tag)) {
				result = new MemoryStream(_data, _index, _readValueLength, false);
			}
			return result;
		}
		/// 
		/// Get the tagged data for a tag.
		/// 
		/// The tag to search for.
		/// Returns a tagged value or null if none found.
		public T GetData()
			where T : class, ITaggedData, new()
		{
			T result = new T();
			if (Find(result.TagID))
			{
				result.SetData(_data, _readValueStart, _readValueLength);
				return result;
			}
			else return null;
		}
		/// 
		/// Get the length of the last value found by 
		/// 
		/// This is only valid if  has previously returned true.
		public int ValueLength {
			get { return _readValueLength; }
		}
		/// 
		/// Get the index for the current read value.
		/// 
		/// This is only valid if  has previously returned true.
		/// Initially the result will be the index of the first byte of actual data.  The value is updated after calls to
		/// ,  and . 
		public int CurrentReadIndex {
			get { return _index; }
		}
		/// 
		/// Get the number of bytes remaining to be read for the current value;
		/// 
		public int UnreadCount {
			get {
				if ((_readValueStart > _data.Length) ||
					(_readValueStart < 4)) {
					throw new ZipException("Find must be called before calling a Read method");
				}
				return _readValueStart + _readValueLength - _index;
			}
		}
		/// 
		/// Find an extra data value
		/// 
		/// The identifier for the value to find.
		/// Returns true if the value was found; false otherwise.
		public bool Find(int headerID)
		{
			_readValueStart = _data.Length;
			_readValueLength = 0;
			_index = 0;
			int localLength = _readValueStart;
			int localTag = headerID - 1;
			// Trailing bytes that cant make up an entry (as there arent enough
			// bytes for a tag and length) are ignored!
			while ((localTag != headerID) && (_index < _data.Length - 3)) {
				localTag = ReadShortInternal();
				localLength = ReadShortInternal();
				if (localTag != headerID) {
					_index += localLength;
				}
			}
			bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length);
			if (result) {
				_readValueStart = _index;
				_readValueLength = localLength;
			}
			return result;
		}
		/// 
		/// Add a new entry to extra data.
		/// 
		/// The  value to add.
		public void AddEntry(ITaggedData taggedData)
		{
			if (taggedData == null) {
				throw new ArgumentNullException("nameof(taggedData)");
			}
			AddEntry(taggedData.TagID, taggedData.GetData());
		}
		/// 
		/// Add a new entry to extra data
		/// 
		/// The ID for this entry.
		/// The data to add.
		/// If the ID already exists its contents are replaced.
		public void AddEntry(int headerID, byte[] fieldData)
		{
			if ((headerID > ushort.MaxValue) || (headerID < 0)) {
				throw new ArgumentOutOfRangeException("nameof(headerID)");
			}
			int addLength = (fieldData == null) ? 0 : fieldData.Length;
			if (addLength > ushort.MaxValue) {
				throw new ArgumentOutOfRangeException("nameof(fieldData)", "exceeds maximum length");
			}
			// Test for new length before adjusting data.
			int newLength = _data.Length + addLength + 4;
			if (Find(headerID)) {
				newLength -= (ValueLength + 4);
			}
			if (newLength > ushort.MaxValue) {
				throw new ZipException("Data exceeds maximum length");
			}
			Delete(headerID);
			byte[] newData = new byte[newLength];
			_data.CopyTo(newData, 0);
			int index = _data.Length;
			_data = newData;
			SetShort(ref index, headerID);
			SetShort(ref index, addLength);
			if (fieldData != null) {
				fieldData.CopyTo(newData, index);
			}
		}
		/// 
		/// Start adding a new entry.
		/// 
		/// Add data using , , , or .
		/// The new entry is completed and actually added by calling 
		/// 
		public void StartNewEntry()
		{
			_newEntry = new MemoryStream();
		}
		/// 
		/// Add entry data added since  using the ID passed.
		/// 
		/// The identifier to use for this entry.
		public void AddNewEntry(int headerID)
		{
			byte[] newData = _newEntry.ToArray();
			_newEntry = null;
			AddEntry(headerID, newData);
		}
		/// 
		/// Add a byte of data to the pending new entry.
		/// 
		/// The byte to add.
		/// 
		public void AddData(byte data)
		{
			_newEntry.WriteByte(data);
		}
		/// 
		/// Add data to a pending new entry.
		/// 
		/// The data to add.
		/// 
		public void AddData(byte[] data)
		{
			if (data == null) {
				throw new ArgumentNullException("nameof(data)");
			}
			_newEntry.Write(data, 0, data.Length);
		}
		/// 
		/// Add a short value in little endian order to the pending new entry.
		/// 
		/// The data to add.
		/// 
		public void AddLeShort(int toAdd)
		{
			unchecked {
				_newEntry.WriteByte((byte)toAdd);
				_newEntry.WriteByte((byte)(toAdd >> 8));
			}
		}
		/// 
		/// Add an integer value in little endian order to the pending new entry.
		/// 
		/// The data to add.
		/// 
		public void AddLeInt(int toAdd)
		{
			unchecked {
				AddLeShort((short)toAdd);
				AddLeShort((short)(toAdd >> 16));
			}
		}
		/// 
		/// Add a long value in little endian order to the pending new entry.
		/// 
		/// The data to add.
		/// 
		public void AddLeLong(long toAdd)
		{
			unchecked {
				AddLeInt((int)(toAdd & 0xffffffff));
				AddLeInt((int)(toAdd >> 32));
			}
		}
		/// 
		/// Delete an extra data field.
		/// 
		/// The identifier of the field to delete.
		/// Returns true if the field was found and deleted.
		public bool Delete(int headerID)
		{
			bool result = false;
			if (Find(headerID)) {
				result = true;
				int trueStart = _readValueStart - 4;
				byte[] newData = new byte[_data.Length - (ValueLength + 4)];
				Array.Copy(_data, 0, newData, 0, trueStart);
				int trueEnd = trueStart + ValueLength + 4;
				Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd);
				_data = newData;
			}
			return result;
		}
		#region Reading Support
		/// 
		/// Read a long in little endian form from the last found data value
		/// 
		/// Returns the long value read.
		public long ReadLong()
		{
			ReadCheck(8);
			return (ReadInt() & 0xffffffff) | (((long)ReadInt()) << 32);
		}
		/// 
		/// Read an integer in little endian form from the last found data value.
		/// 
		/// Returns the integer read.
		public int ReadInt()
		{
			ReadCheck(4);
			int result = _data[_index] + (_data[_index + 1] << 8) +
				(_data[_index + 2] << 16) + (_data[_index + 3] << 24);
			_index += 4;
			return result;
		}
		/// 
		/// Read a short value in little endian form from the last found data value.
		/// 
		/// Returns the short value read.
		public int ReadShort()
		{
			ReadCheck(2);
			int result = _data[_index] + (_data[_index + 1] << 8);
			_index += 2;
			return result;
		}
		/// 
		/// Read a byte from an extra data
		/// 
		/// The byte value read or -1 if the end of data has been reached.
		public int ReadByte()
		{
			int result = -1;
			if ((_index < _data.Length) && (_readValueStart + _readValueLength > _index)) {
				result = _data[_index];
				_index += 1;
			}
			return result;
		}
		/// 
		/// Skip data during reading.
		/// 
		/// The number of bytes to skip.
		public void Skip(int amount)
		{
			ReadCheck(amount);
			_index += amount;
		}
		void ReadCheck(int length)
		{
			if ((_readValueStart > _data.Length) ||
				(_readValueStart < 4)) {
				throw new ZipException("Find must be called before calling a Read method");
			}
			if (_index > _readValueStart + _readValueLength - length) {
				throw new ZipException("End of extra data");
			}
			if (_index + length < 4) {
				throw new ZipException("Cannot read before start of tag");
			}
		}
		/// 
		/// Internal form of  that reads data at any location.
		/// 
		/// Returns the short value read.
		int ReadShortInternal()
		{
			if (_index > _data.Length - 2) {
				throw new ZipException("End of extra data");
			}
			int result = _data[_index] + (_data[_index + 1] << 8);
			_index += 2;
			return result;
		}
		void SetShort(ref int index, int source)
		{
			_data[index] = (byte)source;
			_data[index + 1] = (byte)(source >> 8);
			index += 2;
		}
		#endregion
		#region IDisposable Members
		/// 
		/// Dispose of this instance.
		/// 
		public void Dispose()
		{
			if (_newEntry != null) {
				_newEntry.Dispose();
			}
		}
		#endregion
		#region Instance Fields
		int _index;
		int _readValueStart;
		int _readValueLength;
		MemoryStream _newEntry;
		byte[] _data;
		#endregion
	}
}