using ConfectioneryBusinessLogic.BusinessLogics;
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using Microsoft.Extensions.Logging;

namespace ConfectioneryBusinessLogic
{
    public class ShopLogic : IShopLogic
    { 
        private readonly ILogger _logger;
        private readonly IShopStorage _shopStorage;
        public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
        {
            _logger = logger;
            _shopStorage = shopStorage;
        }
        public List<ShopViewModel>? ReadList(ShopSearchModel? model)
        {
            _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id} ",
                model?.Name, model?.Id);
            var list = (model == null) ? _shopStorage.GetFullList() :
            _shopStorage.GetFilteredList(model);
            if (list == null)
            {
                _logger.LogWarning("ReadList return null list");
                return null;
            }
            _logger.LogInformation("ReadList. Count:{Count}", list.Count);
            return list;
        }
        public ShopViewModel? ReadElement(ShopSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}",
                model.Name, model.Id);
            var element = _shopStorage.GetElement(model);
            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }
            _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
            return element;
        }
        public bool Create(ShopBindingModel model)
        {
            CheckModel(model);
            model.Pastries = new();
            if (_shopStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }
        public bool Update(ShopBindingModel model)
        {
            CheckModel(model, false);
            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException("Нет названия магазина",
                nameof(model.Name));
            }
            if (_shopStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }
        public bool Delete(ShopBindingModel model)
        {
            CheckModel(model, false);
            _logger.LogInformation("Delete. Id:{Id}", model.Id);
            if (_shopStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");
                return false;
            }
            return true;
        }
        private void CheckModel(ShopBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException("Нет названия магазина",
                nameof(model.Name));
            }
            if (model.MaxCountPastries < 0)
            {
                throw new ArgumentException(
                    "Максимальное количество изделий в магазине не должно быть отрицательным",
                    nameof(model.MaxCountPastries));
            }

            _logger.LogInformation("Shop. ShopName:{0}.Address:{1}. Id: {2}",
                model.Name, model.Address, model.Id);
            var element = _shopStorage.GetElement(new ShopSearchModel
            {
                Name = model.Name
            });
            if (element != null && element.Id != model.Id && element.Name == model.Name)
            {
                throw new InvalidOperationException("Магазин с таким названием уже есть");
            }
        }

        public bool AddPastry(ShopSearchModel model, IPastryModel pastry, int count)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (count <= 0)
            {
                throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(count));
            }
            _logger.LogInformation("AddPastryInShop. ShopName:{ShopName}.Id:{ Id}",
                model.Name, model.Id);
            var element = _shopStorage.GetElement(model);
            if (element == null)
            {
                _logger.LogWarning("AddPastryInShop element not found");
                return false;
            }
            _logger.LogInformation("AddPastryInShop find. Id:{Id}", element.Id);

            var currentCountPasties = element.Pastries.Select(x => x.Value.Item2).Sum();
            if (currentCountPasties + count > element.MaxCountPastries)
            {
                _logger.LogWarning("AddPastryInShop. The number of pastry {count} exceeds maximum {max}",
                    currentCountPasties + count, element.MaxCountPastries);
                return false;
            }
            if (element.Pastries.TryGetValue(pastry.Id, out var pair))
            {
                element.Pastries[pastry.Id] = (pastry, count + pair.Item2);
            }
            else
            {
                element.Pastries[pastry.Id] = (pastry, count);
            }
            _logger.LogInformation(
                    "AddPastryInShop. Has been added {count} {pastry} in {ShopName}",
                    count, pastry.PastryName, element.Name);
            _shopStorage.Update(new()
            {
                Id = element.Id,
                Address = element.Address,
                Name = element.Name,
                DateOpening = element.DateOpening,
                Pastries = element.Pastries
            });
            return true;
        }


        public int GetFreePlacesWithPastriesInShops(int countPastries)
        {
            // Сумма разностей между максимальный кол-вом изделий и суммой всех изделий в магазине
            return _shopStorage.GetFullList()
                .Select(x => x.MaxCountPastries - x.Pastries
                    .Select(p => p.Value.Item2).Sum())
                .Sum() - countPastries;
        }

        public bool AddPastriesInShops(IPastryModel pastry, int count)
        {
            var freePlaces = GetFreePlacesWithPastriesInShops(count);
            if (freePlaces < 0)
            {
                _logger.LogInformation("AddPastriesInShops. Не удалось добавить изделия в магазины, поскольку они переполнены." +
                    $"Освободите магазины на {-freePlaces} изделий");
                return false;
            }
            foreach (var shop in _shopStorage.GetFullList())
            {
                var cnt = Math.Min(count, shop.MaxCountPastries - shop.Pastries.Select(x => x.Value.Item2).Sum());
                if (!AddPastry(new() { Id = shop.Id }, pastry, cnt))
                {
                    _logger.LogWarning("При добавления изделий во все магазины произошла ошибка");
                    return false;
                }
                count -= cnt;
                if (count == 0)
                {
                    return true;
                }
            }
            return true;
        }
    }
}