using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SystemX.Common.Util
{
    public static class Gzip
    {
        #region Functions
        public static string Compress(string stringData)
        {
            var rowData = Encoding.UTF8.GetBytes(stringData);
            byte[] compressedData = null;
            using (var outStream = new MemoryStream())
            {
                using (var gStream = new GZipStream(outStream, CompressionMode.Compress))
                {
                    gStream.Write(rowData, 0, rowData.Length);
                }
                compressedData = outStream.ToArray();
            }

            return Convert.ToBase64String(compressedData);
        }

        public static string Decompression(string compressedDataStr)
        {
            string output = null;
            byte[] compressedData = Convert.FromBase64String(compressedDataStr);
            using (var decompressStream = new MemoryStream(compressedData))
            {
                using (var gStream = new GZipStream(decompressStream, CompressionMode.Decompress))
                {                   
                    using (var reader = new StreamReader(gStream))
                    {
                        output = reader.ReadToEnd();
                    }
                }
            }

            return output;
        }
        #endregion

        #region String Extension(확장메서드)
        public static string GzipCompress(this string stringData)
        {
            return Compress(stringData);
        }

        public static string GzipDecompress(this string compressedDataStr)
        {
            return Decompression(compressedDataStr);
        }
        #endregion
    }
}
