using System;
using System.IO;

namespace BS.Shared.Core
{
    public class ProgressStream : Stream, IDisposable
    {
        private readonly Stream _Stream;

        private long bytesRead;

        public ProgressStream(Stream pStream)
        {
            this._Stream = pStream;
            this.bytesRead = 0;
        }

        public event EventHandler<EventArgs<double>> ProgressChanged;

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return false;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        public override long Length
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }

        public override long Position
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }

            set
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }

        public double Progress
        {
            get
            {
                return ((double)this.bytesRead) / this._Stream.Length;
            }
        }

        public override void Flush()
        {
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int result = this._Stream.Read(buffer, offset, count);
            this.bytesRead += result;
            if (this.ProgressChanged != null)
            {
                this.ProgressChanged(this, new EventArgs<double>(this.Progress));
            }

            return result;
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void SetLength(long value)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new Exception("The method or operation is not implemented.");
        }

	    public new void Dispose()
	    {
		    if (_Stream != null)
		    {
			    _Stream.Close();
				_Stream.Dispose();
		    }
		    base.Dispose();
	    }
    }
}