using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;

namespace DeviceRepair.Utils
{
    /// <summary>
    /// 数据 GZip压缩
    /// </summary>
    public static class CompressionHelper
    {
        #region 对象转byte[]
        /// <summary>
        /// 转数据集并压缩
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ToArrayAndCompress(this object obj)
        {
            if (obj == null)
                return null;

            byte[] bytes;
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                formatter.Serialize(memoryStream, obj);
                bytes = memoryStream.ToArray();
            }
            return Compress(bytes);
        }

        /// <summary>
        /// 解压缩并转化到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T DecompressAndSerializeObject<T>(this byte[] bytes) where T : class
        {
            byte[] debyte = Decompress(bytes);
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(debyte))
            {
                object obj = formatter.Deserialize(stream);
                return (T)obj;
            }
        }
        #endregion

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Compress(this byte[] data)
        {
            using (var compressedStream = new MemoryStream())
            {
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
                {
                    zipStream.Write(data, 0, data.Length);
                    zipStream.Close();
                    return compressedStream.ToArray();
                }
            }
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Decompress(this byte[] data)
        {
            using (var compressedStream = new MemoryStream(data))
            {
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                {
                    using (var resultStream = new MemoryStream())
                    {
                        zipStream.CopyTo(resultStream);
                        return resultStream.ToArray();
                    }
                }
            }
        }
    }
}
