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

namespace Tiobon.Core.OPS.Tool.OPS.Tool.Helper
{
    /// <summary>
    /// 
    /// </summary>
    public class HttpHelper
    {

        #region HTTP模板
        private static CookieContainer m_Cookies = new CookieContainer();
        public enum Compression
        {
            GZip,
            Deflate,
            None,
        }

        /// <summary>
        /// 获取HttpWebRequest模板
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="postdata">POST</param>
        /// <param name="cookies">Cookies</param>
        /// <returns></returns>
        private static HttpWebRequest GetHttpRequest(string url, string postdata, CookieContainer cookies)
        {
            HttpWebRequest request = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;
            request.ContentType = "application/json";
            request.ServicePoint.ConnectionLimit = 300;
            ServicePointManager.Expect100Continue = false;
            request.Referer = url;
            request.Accept = "*/*";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            request.AllowAutoRedirect = true;
            if (postdata != null && postdata != "")
            {
                request.Method = "POST";
                byte[] byte_post = Encoding.Default.GetBytes(postdata);
                request.ContentLength = byte_post.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(byte_post, 0, byte_post.Length);
                }
            }
            else
            {
                request.Method = "GET";
            }
            return request;
        }

        /// <summary>
        /// 提取HttpWebResponse文本内容
        /// </summary>
        /// <param name="resp">HttpWebResponse响应包</param>
        /// <returns></returns>
        private static string GetResponseContent(HttpWebResponse resp)
        {

            if (resp.StatusCode != HttpStatusCode.OK)
                throw new Exception("远程服务器返回状态码: " + resp.StatusCode);

            Encoding enc = Encoding.UTF8;
            if (resp.CharacterSet != null && resp.CharacterSet != "")
                enc = Encoding.GetEncoding(resp.CharacterSet);

            Compression comp = Compression.None;
            if (resp.ContentEncoding != null && resp.ContentEncoding.Trim().ToUpper() == "GZIP")
                comp = Compression.GZip;
            else if (resp.ContentEncoding != null && resp.ContentEncoding.Trim().ToUpper() == "DEFLATE")
                comp = Compression.Deflate;

            MemoryStream ms = new MemoryStream();
            using (StreamWriter sw = new StreamWriter(ms, enc))
            {
                StreamReader sr;
                switch (comp)
                {
                    case Compression.GZip:
                        sr = new StreamReader(new System.IO.Compression.GZipStream(resp.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress), enc);
                        break;
                    case Compression.Deflate:
                        sr = new StreamReader(new System.IO.Compression.DeflateStream(resp.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress), enc);
                        break;
                    default:
                        sr = new StreamReader(resp.GetResponseStream(), enc);
                        break;
                }

                while (!sr.EndOfStream)
                {
                    char[] buf = new char[16000];
                    int read = sr.ReadBlock(buf, 0, 16000);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(buf, 0, read);
                    sw.Write(buf, 0, read);
                }
                sr.Close();
            }

            byte[] mbuf = ms.GetBuffer();
            string sbuf = enc.GetString(mbuf);
            return sbuf;
        }

        /// <summary>
        /// 获取HttpWebRequest返回值
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="postdata">PostData</param>
        /// <returns></returns>
        public static string GetHttpResult(string url, string postdata = null)
        {
            try
            {
                HttpWebRequest request = GetHttpRequest(url, postdata, m_Cookies);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //m_Cookies.Add(response.Cookies);

                string res = GetResponseContent(response);
                return res;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion
    }
}
