using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Models;
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 AssemblyLogic : IAssemblyLogic
    {
        private readonly ILogger _logger;
        private readonly IAssemblyStorage _assemblyStorage;
        private readonly IComponentStorage _componentStorage;

        public AssemblyLogic(ILogger<AssemblyLogic> logger, IAssemblyStorage assemblyStorage, IComponentStorage componentStorage)
        {
            _logger = logger;
            _assemblyStorage = assemblyStorage;
            _componentStorage = componentStorage;
        }

        public bool Create(AssemblyBindingModel model)
        {
            CheckModel(model);
            if (_assemblyStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }

        public bool Delete(AssemblyBindingModel model)
        {
            CheckModel(model, false);
            _logger.LogInformation("Delete. Id:{Id}", model.Id);
            if (_assemblyStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");
                return false;
            }
            return true;
        }

        public AssemblyViewModel? ReadElement(AssemblySearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            _logger.LogInformation("ReadElement. AssemblyName:{AssemblyName}.Id:{ Id}", model.AssemblyName, model.Id);
            var element = _assemblyStorage.GetElement(model);
            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }
            _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
            return element;
        }

        public List<AssemblyViewModel>? ReadList(AssemblySearchModel? model)
        {
            _logger.LogInformation("ReadList. AssemblyName:{AssemblyName}.Id:{ Id}", model?.AssemblyName, model?.Id);
            var list = model == null ? _assemblyStorage.GetFullList() : _assemblyStorage.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(AssemblyBindingModel model)
        {
            CheckModel(model);
            if (_assemblyStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }

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

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

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

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

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

            _assemblyStorage.Update(new()
            {
                Id = element.Id,
                AssemblyName = element.AssemblyName,
                Price = element.Price + component.Cost * amount,
                ClientId = element.ClientId,
                AssemblyComponents = element.AssemblyComponents,
            });

            return true;
        }

        private void CheckModel(AssemblyBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (string.IsNullOrEmpty(model.AssemblyName))
            {
                throw new ArgumentNullException("Нет названия сборки", nameof(model.AssemblyName));
            }
            if (model.Price <= 0)
            {
                throw new ArgumentNullException("Стоимость сборки должна быть больше 0", nameof(model.Price));
            }
            _logger.LogInformation("Assembly. ComputerName:{AssemblyName}.Price:{ Price}. Id: { Id}", model.AssemblyName, model.Price, model.Id);
            var element = _assemblyStorage.GetElement(new AssemblySearchModel
            {
                AssemblyName = model.AssemblyName
            });
            if (element != null && element.Id != model.Id)
            {
                throw new InvalidOperationException("Сборка с таким названием уже есть");
            }
        }
    }
}
