using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Enums;
using DocumentFormat.OpenXml.Drawing.Diagrams;
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 _componentStorage;
        public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IAssemblyStorage componentStorage)
        {
            _logger = logger;
            _orderStorage = orderStorage;
            _componentStorage = componentStorage;
        }
        public OrderViewModel? CreateOrder(OrderBindingModel model)
        {
            CheckModel(model);
			if (model.Status != OrderStatus.Неизвестен)
            {
                _logger.LogWarning("Order status is incorrect");
                return null;
            }
            model.Status = OrderStatus.Принят;
            var new_order = _orderStorage.Insert(model);

			if (new_order == null) 
            {
                Console.WriteLine("_orderStorage.Insert(model) == null");
                model.Status = OrderStatus.Неизвестен;
                _logger.LogWarning("Failed to insert order into a storage");     
                return null;
            }
            return new_order;
        }
        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 OrderViewModel? ReadElement(OrderSearchModel? model)
        {
            _logger.LogInformation("GetElement. Orderid:{ Id}", model?.Id);
            var order = new OrderViewModel();
            if (model == null)
                order = null;
            else
                order = _orderStorage.GetElement(model);

            if (order == null)
            {
                _logger.LogWarning("Get element returned null");
            }
            _logger.LogInformation("Read element currect");
            return order;
        }

        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 rawModel, OrderStatus _newStatus)
		{
			var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = rawModel.Id });
			if (viewModel == null)
			{
				_logger.LogWarning("Order model not found");
				return false;
			}
			
			CheckModel(rawModel, false);
			if (rawModel.Status + 1 != _newStatus)
			{
				_logger.LogWarning("Status update to " + _newStatus.ToString() + " operation failed. Order status incorrect.");
				return false;
			}
			rawModel.Status = _newStatus;
			if (rawModel.Status == OrderStatus.Выдан)
                rawModel.DateImplement = DateTime.Now;

			if (_orderStorage.Update(rawModel) == null)
			{
				rawModel.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)
            {
                
            }
            _logger.LogInformation("Order. OrderID:{Id}. Sum:{ Sum}. ClientId: { ClientId}", model.Id, model.Sum, model.ClientId);
        }

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

			_logger.LogInformation("AddComponentToAssembly. AssemblyName:{AssemblyName}.Id:{ Id}", model.ClientId, model.Id);
			var element = _orderStorage.GetElement(model);
			var component = _componentStorage.GetElement(componentmodel);

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

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

            element.OrderAssemblies[component.Id] = (component, amount);


            var order_binding = new OrderBindingModel()
            {
                Id = element.Id,
                Status = element.Status,
                DateCreate = element.DateCreate,
                DateImplement = element.DateImplement,
                Sum = element.Sum + component.Price * amount,
                ClientId = element.ClientId,
                OrderAssemblies = element.OrderAssemblies,
            };

			_orderStorage.Update(order_binding);

			return true;
		}

    }
}
