using System.Net.Http;
using System.Text;
using SepehrHotelApiSampleClient.ApiException;

namespace SepehrHotelApiSampleClient
{
    public class HttpClientHelper
    {
        public static string Post(
            string url,
            string content)
        {
            // add gzip header, so response will be compressed
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
            };

            // don't dispose HttpClient in production code: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
            using (var httpClient = new HttpClient(handler))
            {
                // ignore HTTPS certificate error
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };

                //Please use Tls 1.2 for connecting to Sepehr websites.
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var httpResponseMessageTask = httpClient.PostAsync(
                    url,
                    new StringContent(content, Encoding.UTF8, "application/json"));

                var httpResponseMessage = httpResponseMessageTask.Result;
                var result = httpResponseMessage.Content.ReadAsStringAsync().Result;

                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    Deserializer.DeserializeResponseAndThrowException(result);
                }

                return result;
            }
        }
    }
}
