using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace EA.FileTalk
{
	public class PlatformBinaryReader
	{
		private bool mBigEndian = false;
		private BinaryReader mBinaryReader;

		public PlatformBinaryReader(bool bigEndian, Stream stream)
		{
			mBigEndian = bigEndian;
			mBinaryReader = new BinaryReader(stream);
		}

		public void Close()
		{
			mBinaryReader.Close();
		}

		/// <summary>
		/// Gets the position within the current stream.
		/// </summary>
		public long Position
		{
			get { return (mBinaryReader.BaseStream.Position); }
		}

		public void ReadPadding(long pad)
		{
			while (pad-- > 0)
				mBinaryReader.Read();
		}

		public void ReadAlignmentPadding(int alignment)
		{
			if (alignment > 0)
			{
				long offset = this.Position % alignment;
				if (offset > 0)
					this.ReadPadding(alignment - offset);
			}
		}

		public uint ReadUint32()
		{
			ReadAlignmentPadding(4);

			if (mBigEndian)
			{
				byte[] uintByteArray = new byte[4];
				for (int i = uintByteArray.Length - 1; i >= 0; i--)
					uintByteArray[i] = mBinaryReader.ReadByte();

				return BitConverter.ToUInt32(uintByteArray, 0);
			}
			else
			{
				return mBinaryReader.ReadUInt32();
			}
		}

		public int ReadInt32()
		{
			ReadAlignmentPadding(4);

			if (mBigEndian)
			{
				byte[] intByteArray = new byte[4];
				for (int i = intByteArray.Length - 1; i >= 0; i--)
					intByteArray[i] = mBinaryReader.ReadByte();

				return BitConverter.ToInt32(intByteArray, 0);
			}
			else
			{
				return mBinaryReader.ReadInt32();
			}
		}

		public bool ReadBool()
		{
			return mBinaryReader.ReadBoolean();
		}

		public string ReadString()
		{
			uint stringLength = ReadUint32()-1;
			byte[] stringByteArray = mBinaryReader.ReadBytes((int)stringLength);
			// read the null character off the stream
			mBinaryReader.ReadByte();
			return System.Text.ASCIIEncoding.ASCII.GetString(stringByteArray);
		}
	}
}
