﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StreamOnReadableDataStorage.cs" company="Microsoft Corporation">
//   Copyright (c) 2008, 2009, 2010 All Rights Reserved, Microsoft Corporation
//
//   This source is subject to the Microsoft Permissive License.
//   Please see the License.txt file for more information.
//   All other rights reserved.
//
//   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
//   KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//   IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//   PARTICULAR PURPOSE.
// </copyright>
// <summary>
//   A class projecing a stream over read only data storage.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Exchange.Data.Internal
{
    using System;
    using System.IO;

    using CtsResources;

    /// <summary>
    /// A class projecing a stream over read only data storage.
    /// </summary>
    internal class StreamOnReadableDataStorage : StreamOnDataStorage, ICloneableStream
    {
        /// <summary>
        /// The starting position in base storage to read from.
        /// </summary>
        private readonly long start;

        /// <summary>
        /// The finishing position in base storage to read to.
        /// </summary>        
        private readonly long end;

        /// <summary>
        /// The base storage instance.
        /// </summary>
        private ReadableDataStorage baseStorage;
        
        /// <summary>
        /// The current position in base storage.
        /// </summary>
        private long position;

        /// <summary>
        /// Value indicating if this instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="StreamOnReadableDataStorage"/> class.
        /// </summary>
        /// <param name="baseStorage">The base storage.</param>
        /// <param name="start">The start position in the base storage to work from.</param>
        /// <param name="end">The end position in the base storage to work to.</param>
        public StreamOnReadableDataStorage(ReadableDataStorage baseStorage, long start, long end)
        {
            InternalDebug.Assert(baseStorage != null || (start == 0 && end == 0));
            InternalDebug.Assert(start >= 0 && start <= end);

            if (baseStorage != null)
            {
                baseStorage.AddRef();
                this.baseStorage = baseStorage;
            }

            this.start = start;
            this.end = end;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="StreamOnReadableDataStorage"/> class.
        /// </summary>
        /// <param name="baseStorage">The base storage.</param>
        /// <param name="start">The start position in the base storage to work from.</param>
        /// <param name="end">The end position in the base storage to work to.</param>
        /// <param name="position">The position to point the internal stream to.</param>
        private StreamOnReadableDataStorage(ReadableDataStorage baseStorage, long start, long end, long position)
        {
            InternalDebug.Assert(baseStorage != null || (start == 0 && end == 0));
            InternalDebug.Assert(start >= 0 && start <= end);

            if (baseStorage != null)
            {
                baseStorage.AddRef();
                this.baseStorage = baseStorage;
            }

            this.start = start;
            this.end = end;
            this.position = position;
        }

        /// <summary>
        /// Gets the storage instance.
        /// </summary>
        /// <value></value>
        public override DataStorage Storage
        {
            get
            {
                this.ThrowIfDisposed();
                return this.baseStorage;
            }
        }

        /// <summary>
        /// Gets the start position for the storage.
        /// </summary>
        /// <value></value>
        public override long Start
        {
            get
            {
                this.ThrowIfDisposed();
                return this.start;
            }
        }

        /// <summary>
        /// Gets the end position for the storage.
        /// </summary>
        /// <value></value>
        public override long End
        {
            get
            {
                this.ThrowIfDisposed();
                return this.end;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <returns>true if the stream supports reading; otherwise, false.
        /// </returns>
        public override bool CanRead
        {
            get
            {
                return !this.disposed;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <returns>true if the stream supports writing; otherwise, false.
        /// </returns>
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports seeking.
        /// </summary>
        /// <returns>true if the stream supports seeking; otherwise, false.
        /// </returns>
        public override bool CanSeek
        {
            get
            {
                return !this.disposed;
            }
        }

        /// <summary>
        /// When overridden in a derived class, gets the length in bytes of the stream.
        /// </summary>
        /// <returns>
        /// A long value representing the length of the stream in bytes.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// A class derived from Stream does not support seeking.
        /// </exception>
        /// <exception cref="T:System.ObjectDisposedException">
        /// Methods were called after the stream was closed.
        /// </exception>
        public override long Length
        {
            get
            {
                this.ThrowIfDisposed();
                
                return this.end == long.MaxValue ? this.baseStorage.Length - this.start : this.end - this.start;
            }
        }

        /// <summary>
        /// Gets or sets the position within the current stream.
        /// </summary>
        /// <returns>
        /// The current position within the stream.
        /// </returns>
        /// <exception cref="T:System.IO.IOException">
        /// An I/O error occurs.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The stream does not support seeking.
        /// </exception>
        /// <exception cref="T:System.ObjectDisposedException">
        /// Methods were called after the stream was closed.
        /// </exception>
        public override long Position
        {
            get
            {
                this.ThrowIfDisposed();
                
                return this.position;
            }

            set
            {
                this.ThrowIfDisposed();
                
                InternalDebug.Assert(0 <= this.Position);

                if (value < 0)
                {                    
                    throw new ArgumentOutOfRangeException("value", SharedStrings.CannotSeekBeforeBeginning);
                }
                
                this.position = value;
            }
        }

        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">
        /// The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.
        /// </exception>
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="buffer"/> is null.
        /// </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// <paramref name="offset"/> or <paramref name="count"/> is negative.
        /// </exception>
        /// <exception cref="T:System.IO.IOException">
        /// An I/O error occurs.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The stream does not support reading.
        /// </exception>
        /// <exception cref="T:System.ObjectDisposedException">
        /// Methods were called after the stream was closed.
        /// </exception>
        public override int Read(byte[] buffer, int offset, int count)
        {
            this.ThrowIfDisposed();

            if (null == buffer)
            {
                throw new ArgumentNullException("buffer");
            }

            if (offset > buffer.Length || offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", SharedStrings.OffsetOutOfRange);
            }

            if (count < 0)
            {                
                throw new ArgumentOutOfRangeException("count", SharedStrings.CountOutOfRange);
            }

            if (count + offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count", SharedStrings.CountTooLarge);
            }

            int readTotal = 0;

            if ((this.end == long.MaxValue || this.position < this.end - this.start) && count != 0)
            {
                if (this.end != long.MaxValue && count > this.end - this.start - this.position)
                {
                    count = (int)(this.end - this.start - this.position);
                }

                int read;
                do
                {
                    read = this.baseStorage.Read(this.start + this.position, buffer, offset, count);

                    count -= read;
                    offset += read;

                    this.position += read;

                    readTotal += read;
                }
                while (count != 0 && read != 0);
            }

            return readTotal;
        }

        /// <summary>
        /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// This operation is not supported in this class.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        /// <exception cref="T:System.NotSupportedException">
        /// When this method is called.
        /// </exception>
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// This operation is not supported in this class.
        /// </summary>
        /// <exception cref="T:System.NotSupportedException">
        /// When this method is called.
        /// </exception>
        public override void Flush()
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Sets the length of the current stream.
        /// This operation is not supported in this class.
        /// </summary>
        /// <param name="value">The desired length of the current stream in bytes.</param>
        /// <exception cref="T:System.NotSupportedException">
        /// When this method is called.
        /// </exception>
        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Sets the position within the current stream.
        /// </summary>
        /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
        /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
        /// <returns>
        /// The new position within the current stream.
        /// </returns>
        /// <exception cref="T:System.IO.IOException">
        /// An I/O error occurs.
        /// </exception>
        /// <exception cref="T:System.NotSupportedException">
        /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
        /// </exception>
        /// <exception cref="T:System.ObjectDisposedException">
        /// Methods were called after the stream was closed.
        /// </exception>
        public override long Seek(long offset, SeekOrigin origin)
        {
            this.ThrowIfDisposed();

            switch (origin)
            {
                case SeekOrigin.Begin:
                    break;
                case SeekOrigin.Current:
                    offset += this.position;
                    break;
                case SeekOrigin.End:
                    offset += this.Length;
                    break;
                default:
                    throw new ArgumentException("Invalid Origin enumeration value", "origin");
            }
            
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", SharedStrings.CannotSeekBeforeBeginning);
            }
            
            this.position = offset;

            return this.position;
        }

        /// <summary>
        /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
        /// </summary>
        public override void Close()
        {
            if (this.baseStorage != null)
            {
                this.baseStorage.Release();
                this.baseStorage = null;
            }

            this.disposed = true;
            base.Close();
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        public Stream Clone()
        {
            this.ThrowIfDisposed();

            return new StreamOnReadableDataStorage(this.baseStorage, this.start, this.end, this.position);
        }

        /// <summary>
        /// Throws an exception if the underlying stream is disposed.
        /// </summary>
        private void ThrowIfDisposed()
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException("StreamOnReadableDataStorage");
            }
        }
    }
}