using HardwareShopContracts.BindingModels;
using HardwareShopContracts.BusinessLogicsContracts;
using HardwareShopContracts.StoragesContracts;
using HardwareShopContracts.ViewModels;

namespace HardwareShopBusinessLogic.BusinessLogics.Storekeeper
{
    public class ReportStorekeeperLogic : IReportStorekeeperLogic
    {
        private readonly IComponentStorage _componentStorage;

        public ReportStorekeeperLogic(IComponentStorage componentStorage)
        {
            _componentStorage = componentStorage;
        }
        public List<ReportBuildGoodViewModel> GetBuildGood(List<GoodViewModel> goods)
        {
            var result = new List<ReportBuildGoodViewModel>();

            foreach (var good in goods)
            {
                var builds = good.GoodComponents
                    //получили сборки и количество компонентов
                    .Select(x => _componentStorage.GetComponentBuilds(new() { Id = x.Key })
                    //если кол-во компонентов в товаре == кол-ву в сборке
                        .Where(y => x.Value.Item2 == y.Item2))
                    .SelectMany(x => x.Select(x => x.Item1))
                    .Distinct()
                    .ToList();
                ReportBuildGoodViewModel record = new()
                {
                    GoodName = good.GoodName,
                    Builds = builds
                };
                result.Add(record);
            }
            return result;
        }
        /// Получение сведений по комплектующим за период, 
        /// с указанием в каких товарах и сборках они использовались
		public List<ReportComponentsViewModel> GetComponents(UserBindingModel user, ReportBindingModel model)
        {
            var result = new List<ReportComponentsViewModel>();
            var components = _componentStorage.GetFilteredList(new()
            {
                UserId = user.Id,
                DateFrom = model.DateFrom,
                DateTo = model.DateTo
            });

            foreach (var component in components)
            {
                var builds = component.ComponentBuilds
                    .Select(x => Tuple.Create(x.Value.Item1.BuildName, x.Value.Item2))
                    .ToList();

                var goods = _componentStorage
                    .GetComponentGoods(new() { Id = component.Id })
                    .ToList();

                ReportComponentsViewModel record = new()
                {
                    ComponentName = component.ComponentName,
                    TotalCount = builds.Sum(x => x.Item2) + goods.Sum(x => x.Item2),
                    GoodOrBuilds = builds.Concat(goods).ToList()
                };

                result.Add(record);
            }
            return result;
        }
    }
}
