namespace Kit.Helpers
{
    using System;
    using Microsoft.AspNetCore.Http;

    public class CookieHelper
    {
        public static string GetValue(string key)
        {
            HttpContext context = HttpContextCore.Current;            
            return GetValue(context, key);
        }

        public static string GetValue(HttpContext context, string key)
        {
            String result = String.Empty;
            if (context != null && context.Request != null && context.Request.Cookies.ContainsKey(key))
            {
                return context.Request.Cookies[key];
            }
            return result;
        }

        public static void SetValue(string key, string value, DateTime expires)
        {
            HttpContext context = HttpContextCore.Current;
            SetValue(context, key, value, expires);
        }

        public static void SetValue(HttpContext context, string key, string value, DateTime expires)
        {
            if (context == null)
            {
                return;
            }

            if (context.Request.Cookies.ContainsKey(key))
            {
                context.Response.Cookies.Delete(key);
            }

            var cookieOptions = new CookieOptions
            {
                Expires = expires
            };
            context.Response.Cookies.Append(key, value, cookieOptions);
        }

        public static void SetValue(string key, string value)
        {
            SetValue(key, value, DateTime.MaxValue);
        }

        public static void SetValue(HttpContext context, string key, string value)
        {
            SetValue(context, key, value, DateTime.MaxValue);
        }

        public static void RemoveCookie(string key)
        {
            HttpContext context = HttpContextCore.Current;
            RemoveCookie(context, key);
        }

        public static void RemoveCookie(HttpContext context, string key)
        {
            if (context == null)
            {
                return;
            }

            CookieOptions cookieOptions = new CookieOptions();
            cookieOptions.Expires = DateTime.Now.AddDays(-30);
            context.Response.Cookies.Delete(key, cookieOptions);
        }
    }
}