using Http.Core.Contexts;
using Http.Core.Exceptions;
using PCUT.Entities;
using PCUT.Entities.ApiResponse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static Http.Core.Constants.HttpConstants;

namespace Http.Core.Extensions
{
    public static class CategoryExtensions
    {
        public static async Task<IEnumerable<Category>> GetCategoriesAsync(this HttpClient client, bool filterByRole = false)
        {
            try
            {
                var response = await client.GetAsync(Api.Categories);
                if (response.IsSuccessStatusCode)
                {
                    var apiResponse = await response.DeserializeObjectAsync<PaginationResponse<IEnumerable<Category>>>();
                    var permittedCategories = apiResponse.Data;
                    if (filterByRole && UserContext.Instance?.Profile?.Role != "admin")
                        permittedCategories = permittedCategories.Where(x => UserContext.Instance.Profile.Permissions.Contains(x.Id));

                    return permittedCategories;
                }
            }
            catch (Exception ex) when (!(ex is AppOutdatedException))
            {
            }
            return Enumerable.Empty<Category>();
        }
    }
}
