using Insight.Infrastructure.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;

namespace Insight.Infrastructure
{
    public static class HttpRequestExtensions
    {
        public static void AddPagination<TData>(this HttpRequest request, PagedList<TData> pagelist)
        {
            var builder = new QueryBuilder();

            foreach (var item in request.Query.Where(p => p.Key.ToLower() != "limit" || p.Key.ToLower() != "offset"))
            {
                builder.Add(item.Key.ToLower(), item.Value.ToString());
            }

            builder.Add("limit", pagelist.Meta.Limit.ToString());

            if (pagelist.Meta.Offset > 0)
            {
                var qb = new QueryBuilder(builder);

                if (pagelist.Meta.Offset > pagelist.Meta.Limit)
                {
                    qb.Add("offset", (pagelist.Meta.Offset - pagelist.Meta.Limit).ToString());
                }
                else
                {
                    qb.Add("offset", 0.ToString());
                }

                pagelist.Meta.Previous = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{qb}";
            }

            if ((pagelist.Meta.Offset + pagelist.Meta.Count) < pagelist.Meta.Total)
            {
                var qb = new QueryBuilder(builder)
                {
                    { "offset", (pagelist.Meta.Offset + pagelist.Meta.Count).ToString() }
                };

                pagelist.Meta.Next = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{qb}";
            }
        }
    }
}