namespace Hims.Infrastructure.Helpers
{
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    using System.Web;
    using Domain.Configurations;
    using Domain.Helpers;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using RestSharp;

    /// <inheritdoc />
    public class URLShortnerHelper : IURLShortnerHelper
    {

        /// <summary>
        /// The application configuration.
        /// </summary>
        private readonly IApplicationConfiguration applicationConfiguration;

        /// <summary>
        /// Initializes a new instance of the <see cref="URLShortnerHelper"/> class.
        /// </summary>
        public URLShortnerHelper(IApplicationConfiguration applicationConfiguration) => this.applicationConfiguration = applicationConfiguration;


        /// <inheritdoc />
        public async Task<string> MakeShorterUrl(string strURL)
        {
            try
            {
                var tinyURLBody = new TinyUrlBody
                {
                    URL = strURL,
                    Domain = "tiny.one",
                    Alias = string.Empty,
                    Tags = string.Empty
                };

                var tinyUrl = new RestClient(this.applicationConfiguration.TinyUrlLink);
                var tinyUrlRequest = new RestRequest(Method.POST);
                tinyUrlRequest.AddQueryParameter("api_token", this.applicationConfiguration.TinyUrlAuthToken);
                tinyUrlRequest.AddHeader("Content-Type", "application/json");
                tinyUrlRequest.AddHeader("Accept", "application/json");
                var test = JsonConvert.SerializeObject(tinyURLBody, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });
                tinyUrlRequest.AddJsonBody(test);

                var shortUrlRequest = await tinyUrl.ExecuteAsync<object>(tinyUrlRequest);
                var shortURl = string.Empty;
                if (shortUrlRequest.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var testObj = JsonConvert.DeserializeObject<TinyURLResponseMainBody>(shortUrlRequest.Content);
                    shortURl += (testObj != null && testObj.Data != null && !string.IsNullOrEmpty(testObj.Data.tiny_url)) ? testObj.Data.tiny_url : strURL;
                }

                return shortURl;
            }
            catch (Exception ex)
            {
                return "-- No URL generated! --";
            }
        }
    }
}