using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Siger.Middlelayer.Common.Helpers
{
    public class HttpClientHelper
    {
        private static readonly HttpClient HttpClient;
        static HttpClientHelper()
        {
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.None,
            };
            HttpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(60) };
        }

        public static string HttpPost(string url, string postData, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
         
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                try
                {
                    var postResult = HttpClient.PostAsync(url, httpContent);
                    postResult.Wait();
                    var response = postResult.Result;
                    //response.EnsureSuccessStatusCode();
                    var resultContent = response.Content.ReadAsStringAsync();
                    resultContent.Wait();
                    return resultContent.Result;
                }
                catch (Exception e)
                {
                    throw new Exception($"HttpPost {url} error: " + e.Message);
                }
            }
        }

        public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            HttpClient.DefaultRequestHeaders.Add("ContentType", contentType);
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }
            try
            {
                var response = HttpClient.GetAsync(url);
                response.Wait();
                var result = response.Result;
                //result.EnsureSuccessStatusCode();
                var resultContent = result.Content.ReadAsStringAsync();
                resultContent.Wait();
                return resultContent.Result;
            }
            catch (Exception e)
            {
                throw new Exception($"HttpGet {url} error: " + e.Message);
            }
        }
    }
}
