// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TempFileStream.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>
//   Creates a unique temporary file stream.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Exchange.Data.Internal
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using System.Threading;
    
    using Win32.SafeHandles;
    using Strings = CtsResources.SharedStrings;

    /// <summary>
    /// Creates a unique temporary file stream.
    /// </summary>
    internal class TempFileStream : FileStream
    {
        /// <summary>
        /// The file location where the file will be created.
        /// </summary>
        private static string tempPath;

        /// <summary>
        /// The next identifier to use for the file name.
        /// </summary>
        private static int nextId = unchecked(Environment.TickCount ^ Process.GetCurrentProcess().Id);

        /// <summary>
        /// Initializes a new instance of the <see cref="TempFileStream"/> class.
        /// </summary>
        /// <param name="handle">The file handle.</param>
        private TempFileStream(SafeFileHandle handle) : base(handle, FileAccess.ReadWrite)
        {
        }

        /// <summary>
        /// Gets the file path.
        /// </summary>
        /// <value>The file path.</value>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", 
            "CA1811:AvoidUncalledPrivateCode", 
            Justification="Both get and set are used upstream. Erroneous FXCop error.")]
        public string FilePath
        {
            get;
            private set;
        }

        // Orphaned WPL code.
#if false
        /// <summary>
        /// Gets the path to the file stream.
        /// </summary>
        /// <value>The path to the file stream..</value>
        internal static string Path
        {
            get
            {
                return GetTempPath();
            }
        }

        /// <summary>
        /// Creates an instance of a temporary file stream.
        /// </summary>
        /// <returns>A new <see cref="TempFileStream"/>.</returns>
        public static TempFileStream CreateInstance()
        {
            return CreateInstance("Cts");
        }

        /// <summary>
        /// Creates an instance of a temporary file stream.
        /// </summary>
        /// <param name="prefix">The file name prefix to use.</param>
        /// <returns>A new <see cref="TempFileStream"/>.</returns>
        public static TempFileStream CreateInstance(string prefix) 
        {
            return CreateInstance(prefix, true);
        }

        /// <summary>
        /// Creates an instance of a temporary file stream.
        /// </summary>
        /// <param name="prefix">The file name prefix to use.</param>
        /// <param name="deleteOnClose">Value indicating if the file should be deleted once it is closed.</param>
        /// <returns>A new <see cref="TempFileStream"/>.</returns>
        public static TempFileStream CreateInstance(string prefix, bool deleteOnClose)
        {
            NativeMethods.SecurityAttributes securityAttribute = new NativeMethods.SecurityAttributes(false);

            string newTempPath = Path;
            
            new FileIOPermission(FileIOPermissionAccess.Write, newTempPath).Demand();

            SafeFileHandle safeHandle;
            string tempFile;
            int errorCode = 0;
            
            int retry = 10;

            do
            {
                uint id = (uint)Interlocked.Increment(ref nextId);

                tempFile =
                    System.IO.Path.Combine(
                        newTempPath,
                        string.Concat(prefix, id.ToString("X5"), ".tmp"));

                uint deleteOnCloseFlag = deleteOnClose ? NativeMethods.FILE_FLAG_DELETE_ON_CLOSE : 0;
                safeHandle = NativeMethods.CreateFile(
                        tempFile,
                        NativeMethods.FILE_GENERIC_READ | NativeMethods.FILE_GENERIC_WRITE,
                        0,
                        ref securityAttribute,
                        NativeMethods.CREATE_NEW,
                        NativeMethods.FILE_ATTRIBUTE_TEMPORARY | deleteOnCloseFlag | NativeMethods.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
                        IntPtr.Zero);

                retry--;

                if (safeHandle.IsInvalid)
                {
                    errorCode = Marshal.GetLastWin32Error();

                    if (errorCode == NativeMethods.ERROR_FILE_EXISTS)
                    {
                        retry++;
                    }
                    
                    Interlocked.Add(ref nextId, Process.GetCurrentProcess().Id);
                }
                else
                {                    
                    retry = 0;
                }
            }
            while (retry > 0);

            if (safeHandle.IsInvalid)
            {
                string message = Strings.CreateFileFailed(tempFile);
                throw new IOException(message, new Win32Exception(errorCode, message));
            }

            TempFileStream tempFileStream = new TempFileStream(safeHandle) { FilePath = tempFile };
            return tempFileStream;
        }

        /// <summary>
        /// Sets the temporary file location.
        /// </summary>
        /// <param name="path">The path in which to create files.</param>
        internal static void SetTemporaryPath(string path)
        {
            tempPath = path;
        }
#endif

        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.IO.FileStream"/> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {            
            try
            {
                base.Dispose(disposing);
            }
            catch (IOException)
            {                
            }
        }

        // Orphaned WPL code.
#if false
        /// <summary>
        /// Returns a file path to the temporary folder.
        /// </summary>
        /// <returns>A file path to the temporary folder.</returns>
        private static string GetTempPath()
        {
            return tempPath ?? (tempPath = System.IO.Path.GetTempPath());
        }
#endif

    }
}

