using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreCacheSample.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace AspNetCoreCacheSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly IMemoryCache _memoryCache;

        private readonly IMemoryCache _myMemoryCache;

        private readonly IDistributedCache _distributedCache;

        public HomeController(IMemoryCache memoryCache,
            IMemoryCache myMemoryCache,
            IDistributedCache distributedCache)
        {
            _memoryCache = memoryCache;
            _myMemoryCache = myMemoryCache;
            _distributedCache = distributedCache;
        }

        public IActionResult GetDateTimeForMemoryCache()
        {
            var dateTime = _memoryCache.Get<DateTime?>("key");

            if (!dateTime.HasValue)
            {
                dateTime = DateTime.Now;
                _memoryCache.Set("key", dateTime, new MemoryCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.Now.AddDays(1),
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1),
                    SlidingExpiration = TimeSpan.FromHours(1)
                });
            }

            DateTime dateTime2 = _memoryCache.GetOrCreate("key", cacheEntiry =>
            {
                cacheEntiry.AbsoluteExpiration = DateTime.Now.AddDays(1);
                return DateTime.Now;
            });

            return Content(dateTime.ToString());
        }

        public IActionResult GetDateTimeForDistributedCache()
        {
            _distributedCache.SetString("key", JsonConvert.SerializeObject(new object()));

            var obj = JsonConvert.DeserializeObject<object>(_distributedCache.GetStringAsync("key").Result);

            _distributedCache.SetAsJsonAsync("key", new object());

            return Content(obj.ToString());
        }

        public IActionResult GetDateTimeForHttpCache()
        {
            Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "public, max-age=600";
            return View(DateTime.Now);
        }

        [ResponseCache(CacheProfileName = "myProfiles")]
        public IActionResult GetDateTimeForHttpCache2()
        {
            return View(DateTime.Now);
        }
    }
}
