namespace Hims.Infrastructure.Helpers
{
    using System;
    using Domain.Helpers;
    using Microsoft.AspNetCore.Http;

    /// <inheritdoc />
    public class CookieHelper : ICookieHelper
    {
        /// <summary>
        /// The http context accessors.
        /// </summary>
        private readonly IHttpContextAccessor httpContextAccessor;

        /// <summary>
        /// Initializes a new instance of the <see cref="CookieHelper"/> class.
        /// </summary>
        /// <param name="httpContextAccessor">
        /// The http context accessor.
        /// </param>
        public CookieHelper(IHttpContextAccessor httpContextAccessor) => this.httpContextAccessor = httpContextAccessor;

        /// <inheritdoc />
        public void Create(string key, string value, int? expireTime)
        {
            var options = new CookieOptions
            {
                Expires = expireTime.HasValue ? DateTime.Now.AddMinutes(expireTime.Value) : DateTime.Now.AddMilliseconds(10)
            };

            this.httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
        }

        /// <inheritdoc />
        public string Get(string key)
        {
            try
            {
                return this.httpContextAccessor.HttpContext.Request.Cookies[key];
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <inheritdoc />
        public void Remove(string key)
        {
            this.httpContextAccessor.HttpContext.Response.Cookies.Delete(key);
        }

        /// <inheritdoc />
        public void DeleteAll(string key)
        {
            var cookiesKeys = this.httpContextAccessor.HttpContext.Request.Cookies.Keys;
            foreach (var cookiesKey in cookiesKeys)
            {
                if (cookiesKey.Contains(key))
                {
                    this.httpContextAccessor.HttpContext.Response.Cookies.Delete(cookiesKey);
                }
            }
        }

        /// <inheritdoc />
        public void DeleteAll()
        {
            var cookiesKeys = this.httpContextAccessor.HttpContext.Request.Cookies.Keys;
            foreach (var cookiesKey in cookiesKeys)
            {
                this.httpContextAccessor.HttpContext.Response.Cookies.Delete(cookiesKey);
            }
        }
    }
}