using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StorageContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;

namespace BlacksmithWorkshopBusinessLogic.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. 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 CreateOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (!CheckStatus(model, OrderStatus.Принят, false)) return false;
            if (_orderStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }
        public bool TakeOrderInWork(OrderBindingModel model)
        {
            CheckModel(model);
            if (!CheckStatus(model, OrderStatus.Выполняется)) return false;
            return true;
        }
        public bool DeliveryOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (!CheckStatus(model, OrderStatus.Выдан)) return false;
            return true;
        }
        public bool FinishOrder(OrderBindingModel model)
        {
            CheckModel(model);
            if (!CheckStatus(model, OrderStatus.Готов)) 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.ManufactureId < 0)
            {
                throw new ArgumentNullException("Некорректный идентификатор компьютера", nameof(model.ManufactureId));
            }
            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. OrderId: {Id}.Sum: {Sum}. ManufactureId: {ManufactureId}", model.Id, model.Sum, model.ManufactureId);
        }

        private bool CheckStatus(OrderBindingModel model, OrderStatus newstatus, bool update = true)
        {
            if (model.Status != newstatus - 1)
            {
                _logger.LogWarning("Failed to change status");
                return false;
            }
            model.Status = newstatus;
            if (!update) return true;
            if (_orderStorage.Update(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
            return true;
        }
    }
}
