using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;

namespace TimedUpload
{
    /// <summary>
    /// Web操作
    /// </summary>
    public static class WebHelper
    {
        #region Host(获取主机名)

        /// <summary>
        /// 获取主机名,即域名,
        /// 范例:用户输入网址http://www.a.com/b.htm?a=1&amp;b=2,
        /// 返回值为: www.a.com
        /// </summary>
        //public static string Host
        //{
        //    get
        //    {
        //        return HttpContext.Current.Request.Url.Host;
        //    }
        //}
        #endregion

        #region HttpWebRequest(请求网络资源)

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源地址</param>
        public static string HttpWebRequest(string url)
        {
            return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源Url地址</param>
        /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
        public static string HttpWebRequest(string url, string parameters, String mehtod)
        {
            return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), mehtod);
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源Url地址</param>
        /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
        public static string HttpWebRequest(string url, string parameters, String mehtod, string contentType)
        {
            return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType);
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源Url地址</param>
        /// <param name="parameters"></param>
        public static string HttpWebRequest(string url, string parameters, string contentType, string Authorization, string app_key)
        {
            return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), "POST", contentType, Authorization, app_key);
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源Url地址</param>
        /// <param name="parameters"></param>
        public static string HttpWebRequest(string url, string parameters, string mehtod, string contentType, string Authorization, string app_key)
        {
            return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType, Authorization, app_key);
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源Url地址</param>
        /// <param name="parameters">提交的参数</param>
        /// <param name="requestBody">提交的requestBody参数json格式</param>
        public static string HttpWebRequest(string url, Dictionary<string, string> parameters,string requestBody)
        {
            return HttpWebRequest(url, null, parameters, requestBody);
        }

        /// <summary>
        /// 请求网络资源,返回响应的文本
        /// </summary>
        /// <param name="url">网络资源地址</param>
        /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
        /// <param name="encoding">字符编码</param>
        /// <param name="isPost">是否Post提交</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="cookie">Cookie容器</param>
        /// <param name="timeout">超时时间</param>
        public static string HttpWebRequest(string url, string parameters, Encoding encoding, string mehtod = "POST",
             string contentType = "application/x-www-form-urlencoded", string Authorization = null, string app_key = null, CookieContainer cookie = null, int timeout = 120000)
        {
            HttpWebRequest request = null;
            try
            {
                if (mehtod == "GET")
                {
                    request = WebRequest.Create(url + (parameters == "" ? "" : "?") + parameters) as HttpWebRequest;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }

                request.Timeout = timeout;
                if (!string.IsNullOrEmpty(Authorization))
                {
                    request.Headers["Authorization"] = Authorization;
                }
                if (!string.IsNullOrEmpty(app_key))
                {
                    request.Headers["app_key"] = app_key;
                }
                request.Headers["AppId"] = Constants.AppId;
                request.CookieContainer = cookie;
                request.ContentType = contentType;
                request.Method = mehtod;

                if (mehtod == "POST")
                {
                    byte[] postData = encoding.GetBytes(parameters);
                    request.ContentType = contentType;
                    request.ContentLength = postData.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(postData, 0, postData.Length);
                    }
                }
                else if(mehtod == "PUT")
                {
                    using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
                    {
                        requestStream.Write(parameters);
                    }
                }
                else if (mehtod == "GET")
                {

                    request.ContentType = "text/html;charset=UTF-8";
                }

                var response = (HttpWebResponse)request.GetResponse();
                string result;
                using (Stream stream = response.GetResponseStream())
                {
                    if (stream == null)
                        return string.Empty;
                    using (var reader = new StreamReader(stream, encoding))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 有Request Paras和Request Body的接口
        /// </summary>
        /// <param name="baseUrl"></param>
        /// <param name="headers"></param>
        /// <param name="urlParas"></param>
        /// <param name="requestBody"></param>
        /// <returns></returns>
        public static string HttpWebRequest(string baseUrl,Dictionary<string, string> headers,Dictionary<string, string> urlParas,string requestBody = null,int timeout = 120000)
        {
            string result ;
            try
            {
                var apiUrl = baseUrl;

                if (urlParas != null)
                {
                    foreach (var p in urlParas)
                    {
                        if (apiUrl.IndexOf("{" + p.Key + "}") > -1)
                        {
                            apiUrl = apiUrl.Replace("{" + p.Key + "}", p.Value);
                        }
                        else
                        {
                            apiUrl += string.Format("{0}{1}={2}", apiUrl.Contains("?") ? "&" : "?", p.Key, p.Value);
                        }
                    }
                }

                var req = (HttpWebRequest)WebRequest.Create(apiUrl);
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Timeout = timeout;
                if (!String.IsNullOrEmpty(requestBody))
                {
                    using (var postStream = new StreamWriter(req.GetRequestStream()))
                    {
                        postStream.Write(requestBody);
                    }
                }

                if (headers != null)
                {
                    if (headers.Keys.Any(p => p.ToLower() == "content-type"))
                        req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
                    if (headers.Keys.Any(p => p.ToLower() == "accept"))
                        req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
                }

                var response = (HttpWebResponse)req.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        result = string.Empty;
                    }
                    else
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                    
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        private static X509Certificate2 GetSentosaCertificate()
        {
            X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            try
            {
                userCaStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
                X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "server", true);
                X509Certificate2 clientCertificate = null;
                if (findResult.Count == 1)
                {
                    clientCertificate = findResult[0];
                }
                else
                {
                    throw new Exception("Unable to locate the correct client certificate.");
                }
                return clientCertificate;
            }
            catch
            {
                throw;
            }
            finally
            {
                userCaStore.Close();
            }
        }
        #endregion

        #region 去除HTML标记
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="NoHTML">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        //public static string NoHtml(string Htmlstring)
        //{
        //    //删除脚本
        //    Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //    //删除HTML
        //    Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
        //    Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
        //    Htmlstring.Replace("<", "");
        //    Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase);
        //    Htmlstring.Replace(">", "");
        //    Htmlstring.Replace("\r\n", "");
        //    Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
        //    return Htmlstring;

        //}
        #endregion

        #region 格式化文本(防止SQL注入)
        /// <summary>
        /// 格式化文本(防止SQL注入)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Formatstr(string html)
        {
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
            html = regex4.Replace(html, ""); //过滤iframe
            html = regex10.Replace(html, "s_elect");
            html = regex11.Replace(html, "u_pudate");
            html = regex12.Replace(html, "d_elete");
            html = html.Replace("'", "’");
            html = html.Replace("&nbsp;", " ");
            return html;
        }
        #endregion
    }
}