using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using PhilExample.Interfaces;

namespace PhilExample.Services
{
    internal class RESTAccess : IRESTAccess
    {
        readonly HttpClient _client = new HttpClient();

        public RESTAccess()
        {
            _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            _client.Timeout = TimeSpan.FromSeconds(10);
        }

        public async Task<T> GetAsync<T>(string url)
        {
            try
            {
                var uri = new Uri(url);
                var response = await _client.GetAsync(uri);
                string responseStr = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseStr))
                    return default;
                else
                    return JsonConvert.DeserializeObject<T>(responseStr);
            }
            catch (Exception ex)
            {
                //await Logger.LogAsync(ex, false);
                return default;
            }
        }

        public async Task<T> PostAsync<T>(string url)
        {
            return await PostAsync<T>(url, null);
        }

        public async Task<T> PostAsync<T>(string url, object postData)
        {
            try
            {
                var uri = new Uri(url);
                var response = await _client.PostAsync(uri, ToHttpContent(postData));
                string responseStr = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseStr))
                    return default;
                else
                    return JsonConvert.DeserializeObject<T>(responseStr);
            }
            catch (Exception ex)
            {
                //await Logger.LogAsync(ex, false);
                return default;
            }
        }

        public async Task<bool> DeleteAsync(string url)
        {
            try
            {
                var uri = new Uri(url);
                var response = await _client.DeleteAsync(uri);
                string responseStr = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseStr))
                    return default;
                else
                    return JsonConvert.DeserializeObject<bool>(responseStr);
            }
            catch (Exception ex)
            {
                //await Logger.LogAsync(ex, false);
                return default;
            }
        }



        #region Helper
        private static HttpContent ToHttpContent(object postData)
        {
            if (postData == null)
                return null;
            string jsonObj = JsonConvert.SerializeObject(postData);
            return new StringContent(jsonObj, Encoding.UTF8, "application/json");
        }
        #endregion
    }
}
