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

namespace EQNetwork.Utility
{
    public class PartialStream : Stream
    {
        private Stream _stream;
        private long _start;
        private long _length;
        public PartialStream(Stream stream, long start, long length)
        {
            _stream = stream;
            _start = start;
            _length = length;
            this.Seek(0, SeekOrigin.Begin);
        }

        public override bool CanRead
        {
            get { return _stream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return _stream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return _stream.CanWrite; }
        }

        public override void Flush()
        {
            _stream.Flush();
        }

        public override long Length
        {
            get { return _length; }
        }

        public override long Position
        {
            get
            {
                return _stream.Position - _start;
            }
            set
            {
                _stream.Position = _start + value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int newCount = count;
            if (_stream.Position + offset + count > _start + _length)
                newCount -= ((int)((_stream.Position + offset + count) - (_start + _length)));
            if (newCount < 0)
                return 0;
            return _stream.Read(buffer, offset, newCount);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin) {
                case SeekOrigin.Begin:
                    return _stream.Seek(_start + offset, origin);
                case SeekOrigin.Current:
                    return _stream.Seek(offset, origin);
                case SeekOrigin.End:
                    return _stream.Seek(_start + _length + offset, origin);
            }
            throw new NotImplementedException();
        }

        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (offset + count > _start + _length)
                count = offset + ((int)((offset + count) - (_start + _length)));
            _stream.Write(buffer, offset, count);
        }
    }
}
