//---------------------------------------------------------------------------------------------
// This file was AUTO-GENERATED by "Lookup Cache Loaders" Xomega.Net generator.
//
// Manual CHANGES to this file WILL BE LOST when the code is regenerated.
//---------------------------------------------------------------------------------------------

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xomega.Framework;
using Xomega.Framework.Lookup;
using Xomega.Framework.Services;

namespace AdventureWorks.Services
{
    public partial class ProductSubcategoryReadListCacheLoader : LookupCacheLoader 
    {
        public ProductSubcategoryReadListCacheLoader(IServiceProvider serviceProvider)
            : base(serviceProvider, LookupCache.Global, true, "product subcategory")
        {
        }

        protected virtual async Task<Output<ICollection<ProductSubcategory_ReadListOutput>>> ReadListAsync()
        {
            using (var s = serviceProvider.CreateScope())
            {
                var svc = s.ServiceProvider.GetService<IProductSubcategoryService>();
                return await svc.ReadListAsync();
            }
        }

        protected override async Task LoadCacheAsync(string tableType, CacheUpdater updateCache, CancellationToken token = default)
        {
            Dictionary<string, Dictionary<string, Header>> data = new Dictionary<string, Dictionary<string, Header>>();
            var output = await ReadListAsync();
            if (output?.Messages != null)
                output.Messages.AbortIfHasErrors();
            else if (output?.Result == null) return;

            foreach (var row in output.Result)
            {
                string type = "product subcategory";

                if (!data.TryGetValue(type, out Dictionary<string, Header> tbl))
                {
                    data[type] = tbl = new Dictionary<string, Header>();
                }
                string id = "" + row.ProductSubcategoryId;
                if (!tbl.TryGetValue(id, out Header h))
                {
                    tbl[id] = h = new Header(type, id, row.Name);
                }
                h.AddToAttribute("product category id", row.ProductCategoryId);
            }
            // if no data is returned we still need to update cache to mark it as loaded
            if (data.Count == 0) updateCache(new LookupTable(tableType, new List<Header>(), true));
            foreach (string type in data.Keys)
                updateCache(new LookupTable(type, data[type].Values, true));
        }
    }
}