using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerDataModels.Enum;
using Microsoft.Extensions.Logging;

namespace DinerBusinessLogic.BusinessLogics
{
    public class OrderLogic : IOrderLogic
    {
        private readonly ILogger _logger;
        private readonly IOrderStorage _orderStorage;
        public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
        {
            _logger = logger;
            _orderStorage = orderStorage;
        }
        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 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 bool CreateOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (model.Status != OrderStatus.Неизвестен) return false;
            model.Status = OrderStatus.Принят;
            if (_orderStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }
       

        public bool FinishOrder(OrderBindingModel model)
        {
            return StatusUpdate(model, OrderStatus.Готов);
        }
      
        private void CheckModel(OrderBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (model.SnackId < 0)
            {
                throw new ArgumentNullException("Неверный идентификатор компонента", nameof(model.SnackId));
            }
            if (model.Count <= 0)
            {
                throw new ArgumentNullException("Количество компонентов должно быть больше 0", nameof(model.Count));
            }
            if (model.Sum <= 0)
            {
                throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
            }
            if (model.ClientId < 0)
            {
                throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientId));
            }
            _logger.LogInformation("Order. ProductId: {ProductId}. Count: {Count}. Sum: {Sum}. Id: {Id}. ClientId: {ClientId}", model.SnackId, model.Count, model.Sum, model.Id, model.ClientId);
            var element = _orderStorage.GetElement(new OrderSearchModel
            {
                Id = model.Id
            });
            if (element != null && element.Id != model.Id)
            {
                throw new InvalidOperationException("Изделие с таким идентификатором уже есть");
            }
        }

		public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus)
		{
			var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });

			if (viewModel == null)
			{
				throw new ArgumentNullException(nameof(model));
			}

			if (viewModel.Status + 1 != newOrderStatus)
			{
				_logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect");
				return false;
			}

			model.Status = newOrderStatus;

			if (viewModel.ImplementerId.HasValue)
			{
				model.ImplementerId = viewModel.ImplementerId;
			}

			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;
		}
		public bool TakeOrderInWork(OrderBindingModel model)
		{
			return StatusUpdate(model, OrderStatus.Выполняется);
		}
		public bool DeliveryOrder(OrderBindingModel model)
		{
			return StatusUpdate(model, OrderStatus.Выдан);
		}
		private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
        {
            CheckModel(model, false);
            var element = _orderStorage.GetElement(new OrderSearchModel()
            {
                Id = model.Id
            });
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }
            model.DateCreate = element.DateCreate;
            model.SnackId = element.SnackId;
            model.DateImplement = element.DateImplement;
            model.Status = element.Status;
            model.Count = element.Count;
            model.Sum = element.Sum;
            if (requiredStatus - model.Status == 1)
            {
                model.Status = requiredStatus;
                if (model.Status == OrderStatus.Выдан)
                    model.DateImplement = DateTime.Now;
                if (_orderStorage.Update(model) == null)
                {
                    _logger.LogWarning("Update operation failed");
                    return false;
                }
                return true;
            }
            _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
            throw new ArgumentException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}");
        }
    }
}

