using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Controllers;
using iiie.CacheControl.Business.OutputCache;
using Newtonsoft.Json;

namespace iiie.CacheControl.Business.CacheKey
{
    public class DefaultCacheKeyGenerator : ICacheKeyGenerator
    {
        public virtual string MakeCacheKey(HttpActionContext context, MediaTypeHeaderValue mediaType,
            OutputCacheType cacheType, bool excludeQueryString = false, bool excludePost = false)
        {
            string parameters = context.Request.Method.Method + "-" + context.Request.RequestUri.AbsolutePath;

            if (!excludeQueryString)
            {
                var pairs = context.Request.GetQueryNameValuePairs().OrderBy(x => x.Key);
                parameters += "?" + string.Join("&", pairs.Select(x => HttpUtility.UrlEncode(x.Key)
                    + "=" + HttpUtility.UrlEncode(x.Value)));
            }
            if (!excludePost)
            {
                parameters += "?" + string.Join("&", context.ActionArguments.Select(x => HttpUtility.UrlEncode(x.Key)
                    + "=" + HttpUtility.UrlEncode(JsonConvert.SerializeObject(x.Value))));
            }

            var cachekey = string.Format("{0}:{1}", parameters, mediaType.MediaType);
            return cachekey;
        }
    }
}
