using System.IO;
using System.IO.Compression;

namespace Siger.Middlelayer.Utility.Helpers
{
    public class CompressionHelper
    {
        public static byte[] DeflateByte(Stream stream)
        {
            if (stream == null)
            {
                return null;
            }

            var str = StreamToBytes(stream);

            using (var output = new MemoryStream())
            {
                using (var compressor = new DeflateStream(output, CompressionMode.Compress))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }

        public static byte[] GzipDeflateByte(Stream stream)
        {
            if (stream == null)
            {
                return null;
            }
            var str = StreamToBytes(stream);

            using (var output = new MemoryStream())
            {
                if (true)
                {
                    using (var gzip = new GZipStream(output, CompressionMode.Compress))
                    {
                        gzip.Write(str, 0, str.Length);
                    }
                }
                return output.ToArray();
            }
        }

        private static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    }
}
