using UnityEngine;
using System.Collections;
using System.IO;

public class XorStream : Stream
{
	private Stream stream;
	private byte[] key;

	public XorStream (Stream stream, byte[] key)
	{
		this.stream = stream;
		this.key = key;
	}

	#region implemented abstract members of Stream

	public override void Flush ()
	{
		this.stream.Flush ();
	}

	public override long Seek (long offset, SeekOrigin origin)
	{
		return this.stream.Seek (offset, origin);
	}

	public override void SetLength (long value)
	{
		this.stream.SetLength (value);
	}

	public override int Read (byte[] buffer, int offset, int count)
	{
		var pos = this.stream.Position;
		var result = this.stream.Read (buffer, offset, count);
		for (int i = 0; i < count; i++) {
			buffer [i + offset] ^= this.key [(pos + i) % this.key.Length];
		}
		return result;
	}

	public override void Write (byte[] buffer, int offset, int count)
	{
		var pos = this.stream.Position;
		for (int i = 0; i < count; i++) {
			buffer [i + offset] ^= this.key [(pos + i) % this.key.Length];
		}
		this.stream.Write (buffer, offset, count);
	}

	public override bool CanRead {
		get {
			return this.stream.CanRead;
		}
	}

	public override bool CanSeek {
		get {
			return this.stream.CanSeek;
		}
	}

	public override bool CanWrite {
		get {
			return this.stream.CanWrite;
		}
	}

	public override long Length {
		get {
			return this.stream.Length;
		}
	}

	public override long Position {
		get {
			return this.stream.Position;
		}
		set {
			this.stream.Position = value;
		}
	}

	#endregion


}
