using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;

namespace WebApi
{
    /// <summary>
    /// 
    /// </summary>
    public class InitServer
    {
        /// <summary>
        /// 
        /// </summary>
        HttpSelfHostConfiguration config = null;
        /// <summary>
        /// 
        /// </summary>
        HttpSelfHostServer server = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="port"></param>
        public InitServer(int port)
        {
            config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}");
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            config.MapHttpAttributeRoutes();
            config.MaxReceivedMessageSize = 1024 * 1024 * 10;
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            // 自定义路由匹配到action
            config.Routes.MapHttpRoute(
                name: "API Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="port"></param>
        public void Init(int port)
        {
           

        }
        public void Close()
        {
            server.CloseAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        public class JsonContentNegotiator : IContentNegotiator
        {
            /// <summary>
            /// 
            /// </summary>
            private readonly JsonMediaTypeFormatter _jsonFormatter;
            /// <summary>
            /// 
            /// </summary>
            /// <param name="formatter"></param>
            public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
            {
                _jsonFormatter = formatter;
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="type"></param>
            /// <param name="request"></param>
            /// <param name="formatters"></param>
            /// <returns></returns>
            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            {
                var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
                return result;
            }

            public static string Postring1(string url, string token, Dictionary<string, string> dic)
            {
                string results = "";
                //url = "http://172.16.22.15:8000/" + url;

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Headers.Add("Authorization", "Bearer " + token);

                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;
                try
                {
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(data, 0, data.Length);
                        reqStream.Close();
                    }
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                    Stream stream = resp.GetResponseStream();
                    //获取响应内容
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        results = reader.ReadToEnd();
                    }
                    return results;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return e.Message;
                    throw;
                }

            }



        }
    }
}
