using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
{
    public class OrderLogic : IOrderLogic
    {
        private readonly ILogger _logger;
        private readonly IOrderStorage _orderStorage;
        private readonly IShopLogic _shopLogic;
        private readonly IManufactureStorage _manufactureStorage;
        private readonly IShopStorage _shopStorage;
        private readonly AbstractMailWorker _mailWorker;
        private readonly IClientLogic _clientLogic;
        static readonly object locker = new object();
        public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, 
            AbstractMailWorker mailWorker, IClientLogic clientLogic, IShopLogic shopLogic, 
            IManufactureStorage manufactureStorage, IShopStorage shopStorage)
        {
            _orderStorage = orderStorage;
            _logger = logger;
            _orderStorage = orderStorage;
            _manufactureStorage = manufactureStorage;
            _shopLogic = shopLogic;
            _shopStorage = shopStorage;
            _mailWorker = mailWorker;
            _clientLogic = clientLogic;
        }
        public OrderViewModel? ReadElement(OrderSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            _logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
            var element = _orderStorage.GetElement(model);
            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }
            _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
            return element;
        }
        public List<OrderViewModel>? ReadList(OrderSearchModel? model)
        {
            _logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
            var list = model == null ? _orderStorage.GetFullList() :
           _orderStorage.GetFilteredList(model);
            if (list == null)
            {
                _logger.LogWarning("ReadList return null list");
                return null;
            }
            _logger.LogInformation("ReadList. Count:{Count}", list.Count);
            return list;
        }
        public bool CreateOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (model.Status != OrderStatus.Неизвестен) return false;
            model.Status = OrderStatus.Принят; 
            var res = _orderStorage.Insert(model);
            if (res == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            SendOrderStatusMail(res.ClientId, $"Изменен статус заказа #{res.Id}", $"Заказ #{res.Id} изменен статус на {model.Status}");
            return true;
        }
        private bool SendOrderStatusMail(int clientId, string subject, string text)
        {
            var client = _clientLogic.ReadElement(new() { Id = clientId });
            if (client == null)
            {
                return false;
            }
            _mailWorker.MailSendAsync(new()
            {
                MailAddress = client.Email,
                Subject = subject,
                Text = text
            });
            return true;
        }

        private bool ChangeStatus(OrderBindingModel model, OrderStatus status)
        {
            CheckModel(model, false);
            var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
            if (element == null)
            {
                _logger.LogWarning("Read operation failed");
                return false;
            }
            if (!(element.Status == status - 1 || element.Status == OrderStatus.Готов))
            {
                _logger.LogWarning("Status change operation failed");
                throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
            }
            if (element.Status == OrderStatus.Готов || element.Status == OrderStatus.Ожидает)
            {
                var manufacture = _manufactureStorage.GetElement(new ManufactureSearchModel() { Id = element.ManufactureId });
                if (manufacture == null)
                {
                    _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
                    return false;
                }
                if (CheckSupply(manufacture, element.Count) == false)
                {
                    _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error.");
                    status = OrderStatus.Ожидает;
                }
            }
            model.Status = status;
            if (model.Status == OrderStatus.Выдан)
                model.DateImplement = DateTime.Now;
            if (element.ImplementerId.HasValue)
                model.ImplementerId = element.ImplementerId;
            var result = _orderStorage.Update(model);
            if (result == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}");
            return true;
        }
        public bool TakeOrderInWork(OrderBindingModel model)
        {
            lock (locker)
            {
                return ChangeStatus(model, OrderStatus.Выполняется);
            }
        }
        public bool FinishOrder(OrderBindingModel model)
        {
            return ChangeStatus(model, OrderStatus.Готов);
        }
        public bool DeliveryOrder(OrderBindingModel model)
        {
            return ChangeStatus(model, OrderStatus.Выдан);
        }
        private void CheckModel(OrderBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (model.Sum <= 0)
            {
                throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
            }
            if (model.Count <= 0)
            {
                throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
            }
            _logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id);
        }
        private bool CheckSupply(IManufactureModel manufacture, int count)
        {
            if (count <= 0)
            {
                _logger.LogWarning("Check then supply operation error. Manufacture count < 0.");
                return false;
            }
            int sumCapacity = 0;
            int sumCount = 0;
            sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
            sumCount = _shopStorage.GetFullList().Select(x => x.ShopManufactures.Select(y => y.Value.Item2).Sum()).Sum();
            int freeSpace = sumCapacity - sumCount;
            if (freeSpace - count < 0)
            {
                _logger.LogWarning("Check then supply operation error. There's no place for new Manufacture in shops.");
                return false;
            }
            foreach (var shop in _shopStorage.GetFullList())
            {
                freeSpace = shop.MaxCapacity;
                foreach (var doc in shop.ShopManufactures)
                {
                    freeSpace -= doc.Value.Item2;
                }
                if (freeSpace == 0)
                {
                    continue;
                }
                if (freeSpace - count >= 0)
                {
                    if (_shopLogic.ReplenishManufactures(new() { Id = shop.Id }, manufacture, count))
                        count = 0;
                    else
                    {
                        _logger.LogWarning("Supply error");
                        return false;
                    }
                }
                if (freeSpace - count < 0)
                {
                    if (_shopLogic.ReplenishManufactures(new() { Id = shop.Id }, manufacture, freeSpace))
                        count -= freeSpace;
                    else
                    {
                        _logger.LogWarning("Supply error");
                        return false;
                    }
                }
                if (count <= 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
