namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_16.Tests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public partial class Program
    {
        public static async ValueTask<byte[]> CompressAsync(byte[] buffer)
        {
            if (buffer.Length == 0)
            {
                return buffer;
            }
            using (MemoryStream memoryStream = new MemoryStream())
            using (System.IO.Compression.GZipStream gZipStream =
                new System.IO.Compression.GZipStream(
                    memoryStream, System.IO.Compression.CompressionMode.Compress))
            {

                await gZipStream.WriteAsync(buffer, 0, buffer.Length);

                buffer = memoryStream.ToArray();

            }

            return buffer;
        }

        public static string UnZip(string value)
        {
            //Przekszta³canie ³ańcucha znaków w tablicź byte[]
            byte[] byteArray = new byte[value.Length];
            int index = 0;
            foreach (char item in value.ToCharArray())
            {
                byteArray[index++] = (byte)item;
            }

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(byteArray))
            using (System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream,
                    System.IO.Compression.CompressionMode.Decompress))
            {

                byteArray = new byte[byteArray.Length];

                //Wypakowywanie
                int bytesRead = gZipStream.Read(byteArray, 0, byteArray.Length);

                //Przekszta³canie tablicy byte[] na ³ańcuch znaków
                StringBuilder data = new System.Text.StringBuilder(bytesRead);
                
                //Wczytywanie tylu bajtów, ile pobrano go gZipStream (zamiast wszystkich
                //bajtów z resultByteArray)
                for (int i = 0; i < bytesRead; i++)
                {
                    data.Append((char)byteArray[i]);
                }
                return data.ToString();
            }
        }
    }
}
