using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using zero.Core.Api;
using zero.Core.Entities;
using zero.Core.Routing;
using zero.Core.Extensions;
namespace zero.Web.ViewHelpers
{
public class ZeroPageHelper : IZeroPageHelper
{
HttpContext HttpContext;
IMediaApi MediaApi;
///
/// Media cache for repetitive queries within an HTTP request
///
Dictionary Cache { get; set; } = new Dictionary();
public ZeroPageHelper(IHttpContextAccessor httpContextAccessor, IMediaApi mediaApi)
{
HttpContext = httpContextAccessor.HttpContext;
MediaApi = mediaApi;
}
///
public async Task GetById(string id)
{
if (id.IsNullOrEmpty())
{
return null;
}
if (!Cache.TryGetValue(id, out IMedia media))
{
media = await MediaApi.GetById(id);
Cache.Add(id, media);
}
return media;
}
///
public async Task> GetByIds(string[] ids)
{
HashSet remoteIds = new HashSet();
Dictionary items = new Dictionary();
foreach (string id in ids)
{
if (Cache.TryGetValue(id, out IMedia media))
{
items.Add(id, media);
}
else
{
remoteIds.Add(id);
}
}
if (remoteIds.Count > 0)
{
Dictionary remoteItems = await MediaApi.GetById(remoteIds);
foreach (var item in remoteItems)
{
items.Add(item.Key, item.Value);
Cache.Add(item.Key, item.Value);
}
}
return items;
}
///
public async Task GetUrl(string id, bool isAbsolute = false)
{
IMedia media = await GetById(id);
return media?.Source;
}
///
public async Task> GetUrls(string[] ids, bool isAbsolute = false)
{
Dictionary medias = await GetByIds(ids);
return medias.ToDictionary(x => x.Key, x => x.Value?.Source);
}
}
public interface IZeroPageHelper
{
///
/// Get media by Id
///
Task GetById(string id);
///
/// Get media items by Ids
///
Task> GetByIds(string[] ids);
///
/// Get source for a media item
///
Task GetUrl(string id, bool isAbsolute = false);
///
/// Get source for media items
///
Task> GetUrls(string[] ids, bool isAbsolute = false);
}
}