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

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();
                    }
                }
            }
        }

        /// <summary>
        /// 将传入字符串以GZip算法压缩后，返回Base64编码字符
        /// </summary>
        /// <param name="rawString">需要压缩的字符串</param>
        /// <returns>压缩后的Base64编码的字符串</returns>
        public static string GZipCompressString(string rawString)
        {
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] rawData = Encoding.UTF8.GetBytes(rawString.ToString());
                byte[] zippedData = Compress(rawData);
                return (string)(Convert.ToBase64String(zippedData));
            }
        }

        /// <summary>
        /// 将gzip压缩后的字符串解压缩
        /// </summary>
        /// <param name="compressedString"></param>
        /// <returns></returns>
        public static string DecompressString(this string compressedString)
        {
            byte[] compressedBytes = Convert.FromBase64String(compressedString);

            using (var inputStream = new MemoryStream(compressedBytes))
            using (var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress))
            using (var outputStream = new MemoryStream())
            {
                gzipStream.CopyTo(outputStream);
                byte[] decompressedBytes = outputStream.ToArray();
                return Encoding.UTF8.GetString(decompressedBytes);
            }
        }

        #region 解压缩

        /// <summary>
        /// 解压数据返回DataSet
        /// </summary>
        /// <param name="addDs"></param>
        /// <returns></returns>
        public static System.Data.DataSet ExactDataSet(byte[] addDs)
        {
            if (addDs == null || addDs.Length == 0)
            {
                return new DataSet();
            }

            byte[] kao = ExactZip(addDs);
            System.Data.DataSet ds = new System.Data.DataSet();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ms.Write(kao, 0, kao.Length);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(ms);
            ds.ReadXml(reader, System.Data.XmlReadMode.Auto);
            ms.Close();
            return ds;
        }

        public static byte[] ExactZip(byte[] needExact)
        {
            System.IO.MemoryStream ret = new System.IO.MemoryStream(needExact);
            System.IO.MemoryStream ret1 = new System.IO.MemoryStream();

            ICSharpCode.SharpZipLib.GZip.GZipInputStream zipIn = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(ret);

            byte[] buffer = new byte[2048];
            int size = 2048;
            while (true)
            {
                size = zipIn.Read(buffer, 0, buffer.Length);
                if (size > 0)
                {
                    ret1.Write(buffer, 0, size);
                }
                else
                {
                    break;
                }
            }
            return ret1.ToArray();
        }

        #endregion
    }
}
