// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.TagHelpers.Internal;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.Mvc.TagHelpers.Cache
{
    /// <summary>
    /// An instance of <see cref="CacheTagKey"/> represents the state of <see cref="CacheTagHelper"/>
    /// or <see cref="DistributedCacheTagHelper"/> keys.
    /// </summary>
    public class CacheTagKey : IEquatable<CacheTagKey>
    {
        private static readonly char[] AttributeSeparator = new[] { ',' };
        private static readonly Func<IRequestCookieCollection, string, string> CookieAcccessor = (c, key) => c[key];
        private static readonly Func<IHeaderDictionary, string, string> HeaderAccessor = (c, key) => c[key];
        private static readonly Func<IQueryCollection, string, string> QueryAccessor = (c, key) => c[key];
        private static readonly Func<RouteValueDictionary, string, string> RouteValueAccessor = (c, key) => c[key]?.ToString();

        private const string CacheKeyTokenSeparator = "||";
        private const string VaryByName = "VaryBy";
        private const string VaryByHeaderName = "VaryByHeader";
        private const string VaryByQueryName = "VaryByQuery";
        private const string VaryByRouteName = "VaryByRoute";
        private const string VaryByCookieName = "VaryByCookie";
        private const string VaryByUserName = "VaryByUser";

        private readonly string _key;
        private readonly string _prefix;
        private readonly string _varyBy;
        private readonly DateTimeOffset? _expiresOn;
        private readonly TimeSpan? _expiresAfter;
        private readonly TimeSpan? _expiresSliding;
        private readonly IList<KeyValuePair<string, string>> _headers;
        private readonly IList<KeyValuePair<string, string>> _queries;
        private readonly IList<KeyValuePair<string, string>> _routeValues;
        private readonly IList<KeyValuePair<string, string>> _cookies;
        private readonly bool _varyByUser;
        private readonly string _username;

        private string _generatedKey;
        private int? _hashcode;

        /// <summary>
        /// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="CacheTagHelper"/>.
        /// </summary>
        /// <param name="tagHelper">The <see cref="CacheTagHelper"/>.</param>
        /// <param name="context">The <see cref="TagHelperContext"/>.</param>
        /// <returns>A new <see cref="CacheTagKey"/>.</returns>
        public CacheTagKey(CacheTagHelper tagHelper, TagHelperContext context)
            : this(tagHelper)
        {
            _key = context.UniqueId;
            _prefix = nameof(CacheTagHelper);
        }

        /// <summary>
        /// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="DistributedCacheTagHelper"/>.
        /// </summary>
        /// <param name="tagHelper">The <see cref="DistributedCacheTagHelper"/>.</param>
        /// <returns>A new <see cref="CacheTagKey"/>.</returns>
        public CacheTagKey(DistributedCacheTagHelper tagHelper)
            : this((CacheTagHelperBase)tagHelper)
        {
            _key = tagHelper.Name;
            _prefix = nameof(DistributedCacheTagHelper);
        }

        private CacheTagKey(CacheTagHelperBase tagHelper)
        {
            var httpContext = tagHelper.ViewContext.HttpContext;
            var request = httpContext.Request;

            _expiresAfter = tagHelper.ExpiresAfter;
            _expiresOn = tagHelper.ExpiresOn;
            _expiresSliding = tagHelper.ExpiresSliding;
            _varyBy = tagHelper.VaryBy;
            _cookies = ExtractCollection(tagHelper.VaryByCookie, request.Cookies, CookieAcccessor);
            _headers = ExtractCollection(tagHelper.VaryByHeader, request.Headers, HeaderAccessor);
            _queries = ExtractCollection(tagHelper.VaryByQuery, request.Query, QueryAccessor);
            _routeValues = ExtractCollection(tagHelper.VaryByRoute, tagHelper.ViewContext.RouteData.Values, RouteValueAccessor);
            _varyByUser = tagHelper.VaryByUser;

            if (_varyByUser)
            {
                _username = httpContext.User?.Identity?.Name;
            }
        }

        /// <summary>
        /// Creates a <see cref="string"/> representation of the key.
        /// </summary>
        /// <returns>A <see cref="string"/> uniquely representing the key.</returns>
        public string GenerateKey()
        {
            // Caching as the key is immutable and it can be called multiple times during a request.
            if (_generatedKey != null)
            {
                return _generatedKey;
            }

            var builder = new StringBuilder(_prefix);
            builder
                .Append(CacheKeyTokenSeparator)
                .Append(_key);

            if (!string.IsNullOrEmpty(_varyBy))
            {
                builder
                    .Append(CacheKeyTokenSeparator)
                    .Append(VaryByName)
                    .Append(CacheKeyTokenSeparator)
                    .Append(_varyBy);
            }

            AddStringCollection(builder, VaryByCookieName, _cookies);
            AddStringCollection(builder, VaryByHeaderName, _headers);
            AddStringCollection(builder, VaryByQueryName, _queries);
            AddStringCollection(builder, VaryByRouteName, _routeValues);

            if (_varyByUser)
            {
                builder
                    .Append(CacheKeyTokenSeparator)
                    .Append(VaryByUserName)
                    .Append(CacheKeyTokenSeparator)
                    .Append(_username);
            }

            _generatedKey = builder.ToString();

            return _generatedKey;
        }

        /// <summary>
        /// Creates a hashed value of the key.
        /// </summary>
        /// <returns>A cryptographic hash of the key.</returns>
        public string GenerateHashedKey()
        {
            var key = GenerateKey();

            // The key is typically too long to be useful, so we use a cryptographic hash
            // as the actual key (better randomization and key distribution, so small vary
            // values will generate dramatically different keys).
            using (var sha256 = CryptographyAlgorithms.CreateSHA256())
            {
                var contentBytes = Encoding.UTF8.GetBytes(key);
                var hashedBytes = sha256.ComputeHash(contentBytes);
                return Convert.ToBase64String(hashedBytes);
            }
        }

        /// <inheritdoc />
        public override bool Equals(object obj)
        {
            var other = obj as CacheTagKey;
            if (other == null)
            {
                return false;
            }

            return Equals(other);
        }

        /// <inheritdoc />
        public bool Equals(CacheTagKey other)
        {
            return string.Equals(other._key, _key, StringComparison.Ordinal) &&
                other._expiresAfter == _expiresAfter &&
                other._expiresOn == _expiresOn &&
                other._expiresSliding == _expiresSliding &&
                string.Equals(other._varyBy, _varyBy, StringComparison.Ordinal) &&
                AreSame(_cookies, other._cookies) &&
                AreSame(_headers, other._headers) &&
                AreSame(_queries, other._queries) &&
                AreSame(_routeValues, other._routeValues) &&
                _varyByUser == other._varyByUser &&
                (!_varyByUser || string.Equals(other._username, _username, StringComparison.Ordinal));
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            // The hashcode is intentionally not using the computed
            // stringified key in order to prevent string allocations
            // in the common case where it's not explicitly required.

            // Caching as the key is immutable and it can be called
            // multiple times during a request.
            if (_hashcode.HasValue)
            {
                return _hashcode.Value;
            }

            var hashCodeCombiner = new HashCodeCombiner();

            hashCodeCombiner.Add(_key, StringComparer.Ordinal);
            hashCodeCombiner.Add(_expiresAfter);
            hashCodeCombiner.Add(_expiresOn);
            hashCodeCombiner.Add(_expiresSliding);
            hashCodeCombiner.Add(_varyBy, StringComparer.Ordinal);
            hashCodeCombiner.Add(_username, StringComparer.Ordinal);

            CombineCollectionHashCode(hashCodeCombiner, VaryByCookieName, _cookies);
            CombineCollectionHashCode(hashCodeCombiner, VaryByHeaderName, _headers);
            CombineCollectionHashCode(hashCodeCombiner, VaryByQueryName, _queries);
            CombineCollectionHashCode(hashCodeCombiner, VaryByRouteName, _routeValues);

            _hashcode = hashCodeCombiner.CombinedHash;

            return _hashcode.Value;
        }

        private static IList<KeyValuePair<string, string>> ExtractCollection<TSourceCollection>(string keys, TSourceCollection collection, Func<TSourceCollection, string, string> accessor)
        {
            if (string.IsNullOrEmpty(keys))
            {
                return null;
            }

            var tokenizer = new StringTokenizer(keys, AttributeSeparator);

            var result = new List<KeyValuePair<string, string>>();

            foreach (var item in tokenizer)
            {
                var trimmedValue = item.Trim();

                if (trimmedValue.Length != 0)
                {
                    var value = accessor(collection, trimmedValue.Value);
                    result.Add(new KeyValuePair<string, string>(trimmedValue.Value, value ?? string.Empty));
                }
            }

            return result;
        }

        private static void AddStringCollection(
            StringBuilder builder,
            string collectionName,
            IList<KeyValuePair<string, string>> values)
        {
            if (values == null || values.Count == 0)
            {
                return;
            }

            // keyName(param1=value1|param2=value2)
            builder
                .Append(CacheKeyTokenSeparator)
                .Append(collectionName)
                .Append("(");

            for (var i = 0; i < values.Count; i++)
            {
                var item = values[i];

                if (i > 0)
                {
                    builder.Append(CacheKeyTokenSeparator);
                }

                builder
                    .Append(item.Key)
                    .Append(CacheKeyTokenSeparator)
                    .Append(item.Value);
            }

            builder.Append(")");
        }

        private static void CombineCollectionHashCode(
            HashCodeCombiner hashCodeCombiner,
            string collectionName,
            IList<KeyValuePair<string, string>> values)
        {
            if (values != null)
            {
                hashCodeCombiner.Add(collectionName, StringComparer.Ordinal);

                for (var i = 0; i < values.Count; i++)
                {
                    var item = values[i];
                    hashCodeCombiner.Add(item.Key);
                    hashCodeCombiner.Add(item.Value);
                }
            }
        }

        private static bool AreSame(IList<KeyValuePair<string, string>> values1, IList<KeyValuePair<string, string>> values2)
        {
            if (values1 == values2)
            {
                return true;
            }

            if (values1 == null || values2 == null || values1.Count != values2.Count)
            {
                return false;
            }

            for (var i = 0; i < values1.Count; i++)
            {
                if (!string.Equals(values1[i].Key, values2[i].Key, StringComparison.Ordinal) ||
                    !string.Equals(values1[i].Value, values2[i].Value, StringComparison.Ordinal))
                {
                    return false;
                }
            }

            return true;
        }
    }
}