using AbstractFoodOrdersBusinessLogic.MailWorker;
using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.BusinessLogicsContracts;
using AbstractFoodOrdersContracts.SearchModels;
using AbstractFoodOrdersContracts.StoragesContracts;
using AbstractFoodOrdersContracts.ViewModels;
using AbstractFoodOrdersDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractFoodOrdersBusinessLogic.BusinessLogics
{
    public class OrderLogic : IOrderLogic
    {
		private readonly ILogger _logger;
		private readonly IOrderStorage _orderStorage;
		private readonly AbstractMailWorker _mailWorker;
		static readonly object _locker = new object();

		public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker)
		{
			_logger = logger;
			_orderStorage = orderStorage;
			_mailWorker = mailWorker;
		}

		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. ClientId: {ClientId}. ImplementerId: {ImplementerId}. Status: {Status}. DateFrom: {DateFrom}. DateTo: {DateTo}. Id: {Id}",
				model.ClientId, model.ImplementerId, model.OrderStatus, model.DateFrom, model.DateTo, 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.Неизвестен)
			{
				_logger.LogWarning("Order status change failed");
				return false;
			}
			model.Status = OrderStatus.Принят;

			var orderView = _orderStorage.Insert(model);
			if (orderView == null)
			{
				_logger.LogWarning("Order creation failed");
				return false;
			}

			Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
			{
				MailAddress = orderView.ClientEmail,
				Subject = $"Новый заказ создан. Заказ №{orderView.Id}",
				Text = $"Заказ №{orderView.Id} от {orderView.DateCreate} на сумму {orderView.Sum} принят."
			}));

			return true;
		}

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

		public bool FinishOrder(OrderBindingModel model)
		{
			return ChangeOrderStatus(model, OrderStatus.Готов);
		}

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

		private void CheckModel(OrderBindingModel model, bool withParams = true)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			if (!withParams)
			{
				return;
			}
			if (model.Count <= 0)
			{
				throw new ArgumentNullException("Кол-во изделий в заказе должно быть больше 0", nameof(model.Count));
			}
			if (model.Sum <= 0)
			{
				throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
			}
			_logger.LogInformation("Order. Count: {Count}. Sum: {Sum} Id: {Id}", model.Count, model.Sum, model.Id);
		}

		private bool ChangeOrderStatus(OrderBindingModel model, OrderStatus newStatus)
		{
			CheckModel(model, false);
			var orderView = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });

			if (orderView == null || newStatus - orderView.Status != 1)
			{
				_logger.LogWarning("Order status change failed");
				return false;
			}

			model.Status = newStatus;
			if (!model.ImplementerId.HasValue)
				model.ImplementerId = orderView.ImplementerId;
			model.DateImplement = orderView.DateImplement;

			if (newStatus == OrderStatus.Готов)
			{
				model.DateImplement = DateTime.Now;
			}

			if (_orderStorage.Update(model) == null)
			{
				_logger.LogWarning("Order status change failed");
				return false;
			}

			Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
			{
				MailAddress = orderView.ClientEmail,
				Subject = $"Заказ №{orderView.Id}",
				Text = $"Заказ №{orderView.Id} изменен статус на {newStatus}."
			}));

			return true;
		}
	}
}
