using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.BusinessLogicsContracts;
using BarContracts.SearchModels;
using BarContracts.ViewModels;
using BarDataModels.Enums;
using Microsoft.Extensions.Logging;

namespace BarBusinessLogic.BusinessLogics
{
    public class WorkModeling : IWorkProcess
    {
        private readonly ILogger _logger;

        private readonly Random _rnd;

        private IOrderLogic? _orderLogic;

        public WorkModeling(ILogger<WorkModeling> Logger)
        {
            _logger = Logger;
            _rnd = new Random(1000);
        }

        public void DoWork(IImplementerLogic ImplementerLogic, IOrderLogic OrderLogic)
        {
            _orderLogic = OrderLogic;
            
            var Implementers = ImplementerLogic.ReadList(null);
            
            if (Implementers == null)
            {
                _logger.LogWarning("DoWork. Implementers is null");
                return;
            }
            
            var Orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Accepted });
            var BeingProcessedOrders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.BeingProcessed });
                // in case there are BeingProcessed orders but no Accepted orders

            if (Orders == null || BeingProcessedOrders == null || (Orders.Count == 0 && BeingProcessedOrders.Count == 0))
            {
                _logger.LogWarning("DoWork. Orders is null or empty");
                return;
            }
            
            _logger.LogDebug("DoWork for {Count} orders", Orders.Count);

            foreach (var Implementer in Implementers)
            {
                Task.Run(() => WorkerWorkAsync(Implementer, Orders));
            }
        }

        private async Task WorkerWorkAsync(ImplementerViewModel Implementer, List<OrderViewModel> Orders)
        {
            if (_orderLogic == null || Implementer == null)
            {
                return;
            }
            
            await RunOrderInWork(Implementer);

            await Task.Run(() =>
            {
                foreach (var Order in Orders)
                {
                    try
                    {
                        _logger.LogDebug("WorkerWorkAsync. Worker {Id} try get order {Order}", Implementer.Id, Order.Id);

                        // TakeOrderInWork will fail when the worker tries to change status to BeingProcessed when the order is already BeingProcessed
                        // which would happen when other worker already acquired that order
                        bool AcquireResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
                        {
                            Id = Order.Id,
                            ImplementerId = Implementer.Id
                        });

                        if (!AcquireResult)
                        {
                            _logger.LogDebug("WorkerWorkAsync. Worker {Id} tried to get order {Order} but it's already acquired by other worker", Implementer.Id, Order.Id);
                            continue;
                        }

                        Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 1000) * Order.Count);
                        
                        _logger.LogDebug("WorkerWorkAsync. Worker {Id} finish order {Order}", Implementer.Id, Order.Id);
                        _orderLogic.FinishOrder(new OrderBindingModel
                        {
                            Id = Order.Id
                        });
                    }
  
                    catch (InvalidOperationException ex)
                    {
                        _logger.LogWarning(ex, "Error try get work");
                    }

                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error while do work");
                        throw;
                    }

                    Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100));
                }
            });
        }

        private async Task RunOrderInWork(ImplementerViewModel Implementer)
        {
            if (_orderLogic == null || Implementer == null)
                return;
            
            try
            {
                var RunOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
                {
                    ImplementerId = Implementer.Id,
                    Status = OrderStatus.BeingProcessed
                }));
                
                if (RunOrder == null)
                {
                    return;
                }

                _logger.LogDebug("RunOrderInWork. Worker {Id} back to order {Order}", Implementer.Id, RunOrder.Id);
                Thread.Sleep(Implementer.WorkExperience * _rnd.Next(100, 300) * RunOrder.Count);
                
                _logger.LogDebug("RunOrderInWork. Worker {Id} finish order {Order}", Implementer.Id, RunOrder.Id);
                _orderLogic.FinishOrder(new OrderBindingModel
                {
                    Id = RunOrder.Id
                });

                Thread.Sleep(Implementer.Qualification * _rnd.Next(10, 100));
            }

            catch (InvalidOperationException ex)
            {
                _logger.LogWarning(ex, "Error try get work");
            }

            catch (Exception ex)
            {
                _logger.LogError(ex, "Error while do work");
                throw;
            }
        }
    }
}
