using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Web;

namespace GreenTree.Nachtragsmanagement.Web.Extensions
{
    public static class ZipArchiveExtension
    {
        /// <summary>
        /// Extracts all entries in a zip file to a target directory on the destination file system
        /// </summary>
        /// <param name="archive">The archive.</param>
        /// <param name="destinationDirectoryName">The target directory path.</param>
        /// <param name="overwrite">Overwrite existing files.</param>
        public static void ExtractToDirectory(this ZipArchive archive, string destinationDirectoryName, bool overwrite)
        {
            if (!overwrite)
            {
                archive.ExtractToDirectory(destinationDirectoryName);

                return;
            }

            foreach (var file in archive.Entries)
            {
                var completeFileName = Path.Combine(destinationDirectoryName, file.FullName);
                var directory = Path.GetDirectoryName(completeFileName);

                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                if (file.Name != "")
                {
                    var memoryStream = file.Open();

                    File.Delete(completeFileName);

                    using (var fileStream = new FileStream(completeFileName, FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        memoryStream.CopyTo(fileStream);
                    }

                    //file.ExtractToFile(completeFileName, true);
                }
            }
        }
    }
}