using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CoderBlog.JSValues
{
    public class JSValues
    {
        //the json object name in javascript
        private const string PageValuesKey = "pageValues";

        public static Dictionary<string, object> GetPageValues(HttpContextBase context)
        {
            var page = context.Items[PageValuesKey] as Dictionary<string, object>;
            if (page == null)
            {
                context.Items[PageValuesKey] = new Dictionary<string, object>();
            }

            return (Dictionary<string, object>)context.Items[PageValuesKey];
        }

        public static Dictionary<string, object> GetPageValues()
        {
            return GetPageValues(new HttpContextWrapper(GetCurrentContext()));
        }

        private static HttpContext GetCurrentContext()
        {
            if (HttpContext.Current == null)
            {
                throw new Exception("HttpContext.Current is null. JSValues needs a HttpContext in order to work.");
            }

            return HttpContext.Current;
        }


        public static void Add(string key, object value)
        {
            var pageValues = GetPageValues();
            if (pageValues.Keys.Contains(key))
            {
                pageValues.Remove(key);
            }

            pageValues.Add(key, value);
        }

        public static void Add(string key, Dictionary<string, object> value, bool clearExisting = false)
        {
            var dictToModify = GetPageValues();

            var existing = dictToModify.FirstOrDefault(r => r.Key == key).Value;
            if (existing != null)
            {
                if (!clearExisting && existing is Dictionary<string, object>)
                {
                    AppendItems(existing as Dictionary<string, object>, value);
                }
                else
                {
                    dictToModify.Remove(key);
                    dictToModify.Add(key, value);
                }
            }
            else
            {
                dictToModify.Add(key, value);
            }
        }

        public static object GetByKey(string key)
        {
            return GetPageValues().FirstOrDefault(r => r.Key == key);
        }

        public static void Clear()
        {
            GetPageValues().Clear();
        }



        private static void AppendItems(Dictionary<string, object> to, Dictionary<string, object> from)
        {
            foreach (var item in from)
            {
                var existing = to.FirstOrDefault(r => item.Key == r.Key).Value;
                if (existing != null)
                {
                    to.Remove(item.Key);
                }

                to.Add(item.Key, item.Value);
            }
        }


    }
}
