using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComputerShopBusinessLogic.BusinessLogics
{
    public class OrderLogic : IOrderLogic
    {
        private readonly ILogger _logger;
        private readonly IOrderStorage _orderStorage;
        private readonly IAssemblyStorage _assemblyStorage;
        private readonly ISupplyStorage _supplyStorage;
        public OrderLogic(ILogger<ComponentLogic> logger, IOrderStorage orderStorage, IAssemblyStorage assemblyStorage, ISupplyStorage supplyStorage)
        {
            _logger = logger;
            _orderStorage = orderStorage;
            _assemblyStorage = assemblyStorage;
            _supplyStorage = supplyStorage;
        }
        public bool CreateOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (_orderStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }
        public List<OrderViewModel>? ReadList(OrderSearchModel? model)
        {
            _logger.LogInformation("ReadList. Orderid:{ 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 Update(OrderBindingModel model)
        {
            CheckModel(model);
            if (_orderStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }
        public bool Delete(OrderBindingModel model)
        {
            CheckModel(model, false);
            _logger.LogInformation("Delete. Id:{Id}", model.Id);
            if (_orderStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");
                return false;
            }
            return true;
        }

        public bool TakeOrderInWork(OrderBindingModel model)
        {
            return StatusUpdate(model, OrderStatus.Выполняется);
        }

        public bool DeliveryOrder(OrderBindingModel model)
        {
            return StatusUpdate(model, OrderStatus.Выдан);
        }

        public bool FinishOrder(OrderBindingModel model)
        {
            return StatusUpdate(model, OrderStatus.Готов);
        }
        
        public bool StatusUpdate(OrderBindingModel model, OrderStatus _newStatus)
        {
            var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
            if (viewModel == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (viewModel.Status + 1 != _newStatus)
            {
                _logger.LogWarning("Status update to " + _newStatus.ToString() + " operation failed. Order status incorrect.");
                return false;
            }
            model.Status = _newStatus;
            if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
            else
            {
                model.DateImplement = viewModel.DateImplement;
            }
            CheckModel(model, false);
            if (_orderStorage.Update(model) == null)
            {
                model.Status--;
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }
        private void CheckModel(OrderBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (model.ClientId < 0)
            {
                throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientId));
            }
            if (model.Sum <= 0)
            {
                throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
            }
            _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. ClientId: { ClientId}", model.Id, model.Sum, model.ClientId);
        }

        public bool AddAssembly(OrderSearchModel model, AssemblySearchModel assemblymodel, int amount)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            _logger.LogInformation("AddAssemblyToOrder. AssemblyName:{AssemblyName}.Id:{ Id}", assemblymodel.AssemblyName, model.Id);
            var element = _orderStorage.GetElement(model);
            var assembly = _assemblyStorage.GetElement(assemblymodel);

            if (element == null || assembly == null)
            {
                return false;
            }

            _logger.LogInformation("AddAssemblyToOrder find. Id:{Id}", element.Id);

            element.AssemblyOrders[assembly.Id] = (assembly, amount);

            _orderStorage.Update(new()
            {
                Id = element.Id,
                Status = element.Status,
                Sum = element.Sum + assembly.Price * amount,
                ClientId = element.ClientId,
                AssemblyOrders = element.AssemblyOrders
            });

            return true;
        }

    }
}
